Home > Blockchain >  Im having a hard time trying to implent subscripts in python since im a bit newer
Im having a hard time trying to implent subscripts in python since im a bit newer

Time:10-10

I have decided to start working on calculating values for An and Bn using a for loop however I cant seem to figure out where I should begin , or is it even neccesary to use subscripts , I cant use variable names since I want the value to sequence of n to increment by 1 in a loop. since the way to calculate An and Bn is to use the value for a0 and b0 and subtract n its very confusing to implemnt this in python since I want the value of n to increment , can anyone help , give me tips and guidance on how to approach this problem its been hard learning online. There is an Image of the equationenter image description here

a0 = int(input('enter a value:')
b0 = int(input('enter a value:')
N = int(input('enter a value:')
n = 0

for i in range(0,N):
    n = n 1
    An=a(n-1) 10
    Bn =10*(b(n-1))
print(An,Bn) # For reference to see if it worked

CodePudding user response:

While the other answer is technically correct, first of all, if you're going to be running a loop incrementing n, doing non-memoized recursion is first of all extremely inefficient as it's O(n^2) both in time and space, and second of all might blow your stack if n gets high enough (which it probably won't).

Instead, first of all, using some very elementary math, you can turn the formula of a_n into a direct formula with no need for the recursive definition - it's just a_0 10n. You can do the same for b_n which is just b_0 * 10 ** n.

Second of all, your syntax doesn't make any sense. f(x) is a function call in python so b(n - 1) means you are calling the function b on the argument n - 1. If you want indexed values, you should be using an array and doing b[n - 1] but in this case a) you can just use the closed form formula for each value of n and b) if you keep track of your current value of a and b starting with the input, you can just keep an accumulator for each and every time you loop just do a = 10 and b *= 10.

Here's how I'd do it. Firstly, your brackets aren't balanced.

a0 = int(input('enter a value:'))
b0 = int(input('enter a value:'))
N = int(input('enter a value:'))

Then, since your value of n is increasing each time, why loop over i and increase n each time and then ignore i? Just run a loop with n.

a = a0
b = b0

for n in range(1, N   1):
    a  = 10
    b *= 10
    # do something with a and b, the current a_n and b_n values

CodePudding user response:

Assuming a and b are >0 ints.

This is how you would do it for a.

def nth_a(n):
    if n <= 0:
        return a0  # Base case
    return nth_a(n - 1)   10

Try it online!

For b do the same thing:

def nth_b(n):
    if n < 2:
        return b0  # Base case
    return nth_b(n - 1) * 10

Try it online!

If you have noticed, an and bn are defined in terms of themselves.

  • Related