Solve #17: Number Letter Counts

  • Thread starter Thread starter Arman777
  • Start date Start date
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
3 replies · 2K views
Arman777
Insights Author
Gold Member
Messages
2,163
Reaction score
191

Homework Statement


https://projecteuler.net/problem=17

Homework Equations

The Attempt at a Solution


Can someone point out where am I doing wrong ? I get some extra numbers but I didnt understand why

Python:
#!/usr/bin/python

A=["one","two","three","four","five","six","seven","eight","nine"]
B=["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"]
C=["twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"]
D=["hundred","thousand","and"]
K=[]
for i in range(len(A)):
    y=len(A[i])
    K.append(y)
for i in range(len(B)):
    y=len(B[i])
    K.append(y)
L=[]
for i in range(8):
    for j in range(9):
        l=len(C[i]+A[j])
        L.append(l)
for i in range(len(C)):
    y=len(C[i])
    L.append(y)
K.extend(L)
l=sum(K)
for i in range(len(A)):
    p=len(D[0]+D[2]+A[i])*len(K)+l
    K.append(p)
for i in range(len(A)):
    y=len(D[0]+A[i])
    K.append(y)
K.append(len(A[0]+D[1]))
h=sum(K)
print(h)

I know that its current until K.extend(L) part then in the middle when I am trying to find the numbers 100-999 something goes wrong but I didnt undersstand why.
Thanks
 
Last edited:
Physics news on Phys.org
I would put print statements throughout your code printing the name and value of each variable so that you can walk through a run and see what an where it went south or if you have a debugger use it to step through your code.
 
  • Like
Likes   Reactions: Arman777
  • Like
Likes   Reactions: StoneTemplePython and Arman777
Mark44 said:
@Arman777, since you're programming in Python, it comes with a simple debugger that would be useful to you. I wrote a couple of Insights articles a while back on this debugger.
https://www.physicsforums.com/insights/simple-python-debugging-pdb-part-1/
https://www.physicsforums.com/insights/simple-python-debugging-pdb-part-2/
Thanks, I ll look at them in detail.

I understand the problem. It's in these lines, very simple error actually.

Python:
for i in range(len(A)):
    p=len(K)*len(A[i]+D[0]+D[2])+l
    K.append(p)
when I say len(K) and then K.append(P), len(K) increases in each append (it goes like 99.100.101 etc ) but it should have been just stayed at 99. So I just changed len(K) with 99 and the problem solved.