Need to make a list from a function - python

I want to change the a variable from 1 to 50 and create an array from the results so that I can feed it into a curve.
The variable is outside the function but the variable changes a value in the function, that is what I need to make a list of.
a=1
def test(foo):
p =a+2
print(p)
test(foo)
I want to get the p values when I change a from 1 to 50:
[3,4,5,6,7,8,9...]

Not sure what you trying to do but if you need a list of numbers with some starting point, you can simply generate them using list comprehension as:
a = 2
x = [i+a for i in range(1, 50)]
print(x)
EDIT: Based on comments from author.
You need to change print to return the generated number. Also, need to add a loop and a list to generate a new number and keep appending the new number to the list.
Note: As said earlier, it is recommended to use Python's supported features like list comprehension as is shown in the original code.
a = 1
def test(i):
p = a + i
return p
res = []
for i in range(2, 50):
res.append(test(i))
print(res)

Related

first list gets auto updated aftter appending another second list to it and then changing the second list in Python

please take a look at this code
a = [int(x) for x in bin(2)[2:]]
coordinates = []
sum = [1,3]
for x in a:
if x == 1:
coordinates.append(sum)
m = ((3*(sum[0]**2)+A) * libnum.invmod(2*sum[1],p)) % p
x3 = (m**2 - 2*sum[0]) % p
sum[1] = ((m*(sum[0]-x3) - sum[1]) + p) % p
sum[0] = x3
my sum list gets updated in the loop and the new values should be added to the coordinates list if they match the conditions. the problem is that after appending the sum list to the coordinates list whenever the values change in sum they also change in coordinates. there is some kind of link between them. Can you please help me with this problem? How can I unlink them so that just the values are appended and stay fixed.
This is because when you assign a list value to a new variable, it only stores the reference number, when you append this variable to a new list, the same reference number is being used. So when you later change the value, it changes the values of the list defined by that reference number, hence changing what that variable stores wherever it was used.
e.g
coordinates = []
some = [1,3] # avoid using 'sum' as variable name as it is a built in function
coordinates.append(some)
print("coordinates initially:", coordinates)
some.append("interesting")
print("coordinates after chaning 'some':", coordinates)
Output:
coordinates initially: [[1, 3]]
coordinates after chaning 'some': [[1, 3, 'interesting']]
This doenst make sense for small lists but when you consider that lists can hold huge amounts of values, it makes it much faster to use reference numbers
Thus, the solution is that we need to infact append a copy of the some list and not just the reference number.
For this, we can do the following:
import copy
# We can use the copy.deepcopy() function and pass it the list we need copied
coordinates.append(copy.deepcopy(some))

How to fix 'int object is not iterable'

I'm trying to add all the integers in the 'a' variable, but this 'a' variable isn't working as a list nor a string, despite having various different integers in it.
I'm writing a Python program that given a positive integer num, provided by the user, prints the sum of all its divisors.
I've already tried to make this 'a' variable a list but the same error happens
import math
num = int(input("Num: "))
a = num + 1 # because range excludes the last number
b = range(1, a)
for i in (b):
x = num / i
if math.floor(x) == x:
c = list(i)
I've already tried to make this 'a' variable a list but the same error happens: 'int object is not iterable'
list() creates a new list, and its argument must be an iterable (e.g. a tuple, another list, etc.). If you only pass one number, i, it won't work.
I suppose what you want to do is not to create a new list with each loop iteration, but add the i element to an already existing list.
You can achieve it this way:
num = int(input("Num: "))
a = num + 1 # because range excludes the last number
b = range(1, a)
divisors = [] # create a new list where the results will be stored
for i in (b):
x = num / i
if math.floor(x) == x:
divisors.append(i) # add the number at the end of the list
If you want to sum all the divisors, use:
sum(divisors)
An even more 'Pythonic' (though, admittedly, not necessarily easier to read if you're not used to list comprehensions) way to achieve the same result would be:
num = int(input("Num: "))
divisors_sum = sum(i for i in range(1, num + 1) if num//i == num/i)
I assume you're using Python 3 here. In Python 3, // is floor division, so you don't have to use math.floor. See this post for more details on // vs. /.
You can create an empty list outside of the loop: c = [], and then each time append an element to the list by c.append(i).

Python Coin Change Dynamic Programming

I am currently trying to implement dynamic programming in Python, but I don't know how to setup the backtracking portion so that it does not repeat permutations.
For example, an input would be (6, [1,5]) and the expected output should be 2 because there are 2 possible ways to arrange 1 and 5 so that their sum is equivalent to 6. Those combinations are {1,1,1,1,1,1} and {1,5} but the way my program currently works, it accounts for the combinations displayed above and the combination {5,1}. This causes the output to be 3 which is not what I wanted. So my question is "How do I prevent from repeating permutations?". My current code is shown below.
import collections as c
class DynamicProgram(object):
def __init__(self):
self.fib_memo = {}
# nested dictionary, collections.defaultdict works better than a regular nested dictionary
self.coin_change_memo = c.defaultdict(dict)
self.__dict__.update({x:k for x, k in locals().items() if x != 'self'})
def coin_change(self, n, coin_array):
# check cache
if n in self.coin_change_memo:
if len(coin_array) in self.coin_change_memo[n]:
return [n][len(coin_array)]
# base cases
if n < 0: return 0
elif n == 1 or n == 0: return 1
result = 0
i = 0
# backtracking (the backbone of how this function works)
while i <= n and i < len(coin_array):
result += self.coin_change(n-coin_array[i], coin_array)
i += 1
# append to cache
self.coin_change_memo[n][len(coin_array)] = result
# return result
return result
One of the way of avoiding permutation is to use the numbers in "non-decreasing" order. By doing so you will never add answer for [5 1] because it is not in "non-decreasing" order.And [1 5] will be added as it is in "non-decreasing" order.
So the change in your code will be if you fix to use the ith number in sorted order than you will never ever use the number which is strictly lower than this.
The code change will be as described in Suparshva's answer with initial list of numbers sorted.
Quick fix would be:
result += self.coin_change(n-coin_array[i], coin_array[i:]) # notice coin_array[i:] instead of coin_array
But you want to avoid this as each time you will be creating a new list.
Better fix would be:
Simply add a parameter lastUsedCoinIndex in the function. Then always use coins with index >= lastUsedCoinIndex from coin array. This will ensure that the solutions are distinct.
Also you will have to make changes in your memo state. You are presently storing sum n and size of array(size of array is not changing in your provided implementation unlike the quick fix I provided, so its of no use there!!) together as a state for memo. Now you will have n and lastUsedCoinIndex, together determining a memo state.
EDIT:
Your function would look like:
def coin_change(self,coin_array,n,lastUsedCoinIndex):
Here, the only variables changing will be n and lastUsedCoinIndex. So you can also modify your constructor such that it takes coin_array as input and then you will access the coin_array initialized by constructor through self.coin_array. Then the function would become simply:
def coin_change(self,n,lastUsedCoinIndex):

Python 2.7: How would I go about creating a dictionary that maps the first n numbers to their respective squares or cubes?

I currently have this piece of code (for squares), but it doesn't seem to be working correctly:
for n in range(len(dict)):
if n == 0:
pass
else:
squares = (n*n)
dict[n]=squares
The parameter of range() should be n, because the dictionary is probably empty when you begin.
Also, dict is a builtin type in python and you shouldn't name your variables this way.
squares = {i:i*i for i in xrange(n)}
dict={}
for i in range(n):
dict[i]=i*i
squares={}
for r in range(int(n) + 1):
if r == 0:
pass;
else:
squares[r] = (r * r)
This code will create a dictionary, look through all of the values up to n, and add the square tot he dictionary at index "r"! This code fulfills all of the requirements you asked for! Let me know if you have any questions!
It's not clear from the question whether dict already contains values. Also I'm not sure why you're skipping n==0.
Assuming you have a list dict with a certain length, your code should work for all values except the first (which you're skipping), except that your last line is not indented, so it's not run inside the loop. This should do it:
for n in range(len(dict)):
dict[n]=n*n
Anyway I recommend a list comprehension to do this:
dict = [n*n for n in len(dict)]

Append a counter to a set

I have a for loop where I count in i in range(0, 999999999) and I want to add these in a set with a second variable, for example (pseudo code):
import random
the_set = set()
for i in range(0, 999999999):
x = random.randint(0,100)
the_set.append(str(i)+":"+str(x))
i and x are example variables where in this case the elements in the set are always unique, I understand that, but with the actual variables non-uniques may occur but shouldn't be in the set.
How do I define such a set and .append() values?
Python set doesn't have append method, but they have add. So, you can do
the_set.add(str(i)+":"+str(x))
In this case, you can simply use set comprehension, like this
the_set = {"{}:{}".format(i, random.randint(0,100)) for i in range(999999999)}
But the actual problem here is 999999999. It is a very big number. So, its not advisable to build a set of that size and holding it in memory. If you are just going to use this as a unique number generator, you can simply use a generator, like this
def get_next_number(max_number):
for i in xrange(max_number): # use `range` if you are using Python 3.x
yield "{}:{}".format(i, random.randint(0,100))
And then you can use it in a loop like this
for new_number in get_next_number(999999999):
print new_number
If I understand correctly, your goal is to ignore x if it has already been generated, I think you might want to use a dictionary instead:
the_dict()
for i in range(0, 999999999):
x = random.randint(0,100)
if the_dict.has_key(x):
continue
the_dict[x] = i
you could build the resulting set afterward:
the_set = {'%i:%i' % (value, key) for key, value in the_dict.iteritems()}
the_set = {'{}:{}'.format(i, random.randint(0,100)) for i in xrange(10)}

Categories

Resources