Skip to content
Advertisement

Iteratively apply a function to an array

I want to create an array that contains g^0, g^1, g^2…. up to g^100 but all to mod50 (apologies if anyone knows how to format this so the powers are properly aligned I need a bit of help!)

In my case g = 23, so I would want an array that looks like:

JavaScript

I’ve included all my (incorrect) code at the bottom for ease of understanding. I have created an empty array with 201 items. I then tried to create a loop which takes i=0 initially and then as we move through each element of the array puts the new value of i as the power of x. I don’t know whether it’s just the code I have made an error with or I need to approach this with a different logic, but regardless any help would be appreciated!

JavaScript

This is the output I am getting from this code:

JavaScript

This initial question has been answered below

I was wondering if the same logic can be applied when instead of g^i as the required outputs, it would be h(g^(-in)) with h = 20, n = 18 and g = 23 as before. I have tried this and am getting incorrect values in my array, code I tried:

JavaScript

Advertisement

Answer

IIUC, you can use a list comprehension:

JavaScript

output:

JavaScript

Or maybe better, using numpy:

JavaScript

output:

JavaScript
why your code failed

You are not doing anything with your array, just using it as a generator of 0s. So the condition i < 100 is always True and x is always 1. Your i = i+1 is overwritten by 0 at each loop.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement