Home > Software engineering >  Iteratively apply a function to an array
Iteratively apply a function to an array

Time:03-18

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:

[1,23,29,17...]

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!

n = 101
array = [0] * n
g = 23
i = 0 

for i in array:
    if i<100:
        x = g**i
        print(xP)
        i = i   1

array

This is the output I am getting from this code:

[1,1,1,1,1...]

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:

h = 20
n = 18
g = 23
array2 = [h*(g**((-i)*n))P0 for i in range(100 1)]

CodePudding user response:

IIUC, you can use a list comprehension:

g = 23
out = [g**iP for i in range(100 1)]

output:

[1, 23, 29, 17, 41, 43, 39, 47, 31, 13, 49, 27, 21, 33, 9, 7, 11, 3, 19, 37, 1, 23, 29, 17, 41, 43, 39, 47, 31, 13, 49, 27, 21, 33, 9, 7, 11, 3, 19, 37, 1, 23, 29, 17, 41, 43, 39, 47, 31, 13, 49, 27, 21, 33, 9, 7, 11, 3, 19, 37, 1, 23, 29, 17, 41, 43, 39, 47, 31, 13, 49, 27, 21, 33, 9, 7, 11, 3, 19, 37, 1, 23, 29, 17, 41, 43, 39, 47, 31, 13, 49, 27, 21, 33, 9, 7, 11, 3, 19, 37, 1]

Or maybe better, using numpy:

import numpy as np
a = 23**np.arange(100 1)P

output:

array([ 1, 23, 29, 17, 41, 43, 39, 47, 31, 13, 49, 27, 21, 33, 43, 33, 49,
       17, 13, 29, 47, 15, 41, 15, 19, 13, 21,  9, 39,  9, 25, 25,  9,  1,
        1, 29,  1, 27, 25,  9, 17, 39, 13, 39, 47, 33, 11, 39, 43, 33, 21,
        5, 31, 29, 19,  9, 25, 43,  5, 21, 13, 33, 49, 43,  9, 29, 29, 49,
       33, 15, 21, 11,  3, 37,  7,  7, 41, 27, 31, 33, 37, 39, 45, 17, 45,
       29, 19, 43, 23, 13, 49, 17,  7, 43, 19, 33, 29, 35, 15, 35,  9])
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.

  • Related