Answer to a "project for beginners"

Updated ywang 0 Tallied Votes 1K Views Share

<<mod edit: answer to this post from the sticky "projects for the beginner">>

#1 * 8 + 1 = 9
#12 * 8 + 2 = 98
#123 * 8 + 3 = 987
#1234 * 8 + 4 = 9876
#12345 * 8 + 5 = 98765
#123456 * 8 + 6 = 987654
#1234567 * 8 + 7 = 9876543
#12345678 * 8 + 8 = 98765432
#123456789 * 8 + 9 = 987654321

def caculate():
    i = 1
    while i <= 9:
        plusone = x2max(i)
        print plusone," * ",8," + ",i," = ",plusone*8+i
        i = i + 1
         
def x2max(i):
    if i == 1:
        return 1
    else:
        return x2max(i-1)*10+i
Legnoduro 13 Newbie Poster

Here is another solution:

numbers = '123456789'
i = 1
j = 0

for num in numbers:
    x = (int(numbers[0:i]))
    y = (int(numbers[j]))
    tot = (int(numbers[0:i])*8+(int(numbers[j])))
    i += 1
    j += 1
    print("%d*8+%d=%d" % (x, y, tot))

1*8+1=9
12*8+2=98
123*8+3=987
1234*8+4=9876
12345*8+5=98765
123456*8+6=987654
1234567*8+7=9876543
12345678*8+8=98765432
123456789*8+9=987654321

bpatt22 0 Newbie Poster
n = 1
for i in (range(1,10)):
    print ("%d*8+%d=%d" % (n, i, (n * 8 + i)))
    n = n * 10 + i + 1

does the n = 1 have to stay outside the for loop?

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

n = 1 has to stay outside the for loop, or you would reset n all the time to 1

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.