Related
I am trying to create a code that will add up a list of numbers which have been squared. I am pretty new to python, so I was wondering if someone could explain why the list1 produced does not include the last number squared. The list2 always seems to start with 0. Can someone explain why?
import math
list2=[]
values=input("Please enter your vector coordinates")
list1=values.split()
print(list1)
for i in range(len(list1)):
value=i**2
list2.append(value)
print(list2)
i is the index, not the value, you can use either indexing:
for i in range(len(list1)):
value = list1[i]**2
list2.append(value)
Or simply use for i in list1:
for i in list1:
value = i**2
list2.append(value)
Even simpler with a list comprehension:
list2 = [i ** 2 for i in list1]
list2 always starts with a 0 because the first value of i is always 0. When you call range(len(list1)), you are asking for all the numbers in the sequence 0, 1, 2, 3, ..., N; where N is the number of elements in list1. Note that these are not the specific elements in list1.
Assuming that list1 has numbers in it, creating list2 with the squares of the corresponding numbers can be achieved in this way:
list2 = []
for num in list1:
v = num**2
list2.append(v)
There's another error in your code: list1 does not contain numbers as desired. In fact, it contains a bunch of strings (each of which looks like a number) but these are strs, not ints. This is because input returns a string, not ints. Continuing from there, values.split() gives you a list of strings, not a list of numbers. So you'll have to cast them to ints yourself:
list1 = [int(v) for v in values.split()]
Here's how I'd write this code:
list2 = []
values = input("Please enter your vector coordinates")
list1 = list(map(int, values.split()))
print(list1)
for num in list1:
list2.append(num**2)
print(list2)
I have a 2d array, how can I delete certain element(s) from it?
x = [[2,3,4,5,2],[5,3,6,7,9,2],[34,5,7],[2,46,7,4,36]]
for i in range(len(x)):
for j in range(len(x[i])):
if x[i][j] == 2:
del x[i][j]
This will destroy the array and returns error "list index out of range".
you can use pop on the list item. For example -
>>> array = [[1,2,3,4], [6,7,8,9]]
>>> array [1].pop(3)
>>> array
[[1, 2, 3, 4], [6, 7, 8]]
I think this can solve your problem.
x = [[2,3,4,5,2],[5,3,6,7,9,2],[34,5,7],[2,46,7,4,36]]
for i in range(len(x)):
for j in range(len(x[i])):
if j<len(x[i]):
if x[i][j] == 2:
del x[i][j]
I have tested it locally and working as expected.Hope it will help.
Mutating a list while iterating over it is always a bad idea. Just make a new list and add everything except those items you want to exclude. Such as:
x = [[2,3,4,5,2],[5,3,6,7,9,2],[34,5,7],[2,46,7,4,36]]
new_array = []
temp = []
delete_val = 2
for list_ in x:
for element in list_:
if element != delete_val:
temp.append(element)
new_array.append(temp)
temp = []
x = new_array
print(x)
Edit: made it a little more pythonic by omitting list indices.
I think this is more readable at the cost of temporarily more memory usage (making a new list) compared to the solution that Sai prateek has offered.
I have a list containing n integers. The ith element of the list a, a[i], can be swapped into any integer x such that 0 ≤ x ≤ a[i]. For example if a[i] is 3, it can take values 0, 1, 2, 3.
The task is to find all permutations of such list. For example, if the list is
my_list = [2,1,4]
then the possible permutations are:
[0,0,0], [0,0,1], ... [0,0,4],
[0,1,0], [0,1,1], ... [0,1,4],
[1,0,0], [1,0,1], ... [1,0,4],
[1,1,0], [1,1,1], ... [1,1,4],
[2,0,0], [2,0,1], ... [2,0,4],
[2,1,0], [2,1,1], ... [2,1,4]
How to find all such permutations?
you could use a comibation of range to get all the 'valid' values for each element of the list and itertools.product:
import itertools
my_list = [2,1,4]
# get a list of lists with all the possible values
plist = [list(range(y+1)) for y in my_list]
#
permutations = sorted(list(itertools.product(*plist)))
more on itertools product see e.g. here on SO or the docs.
Here's a solution:
my_list=[2,1,4]
def premutation_list(p_list):
the_number=int("".join(map(str,p_list)))
total_len=len(str(the_number))
a=[i for i in range(the_number)]
r_list=[]
for i in a:
if len(str(i))<total_len:
add_rate=total_len - len(str(i))
b="0,"*add_rate
b=b.split(",")
b=b[0:len(b)-1]
b.append(str(i))
r_list.append([int(y) for x in b for y in x ])
else:
r_list.append([int(x) for x in str(i)])
return r_list
print(premutation_list(my_list))
Explanation:
The basic idea is just getting all the numbers till the given number. For example till 4 there are 0,1,2,3, number.
I have achieved this first by converting the list into a integer.
Then getting all the numbers till the_number.
Try this. Let me know if I misunderstood your question
def permute(l,cnt,n):
if cnt==n:
print(l)
return
limit = l[cnt]
for i in range(limit+1):
l[cnt]=i
permute(l[:n],cnt+1,n)
l =[2,1,4]
permute(l,0,3)
Lets say I have a list with three arrays as following:
[(1,2,0),(2,9,6),(2,3,6)]
Is it possible I get the average by diving each "slot" of the arrays in the list.
For example:
(1+2+2)/3, (2+0+9)/3, (0+6+6)/3
and make it become new arraylist with only 3 integers.
You can use zip to associate all of the elements in each of the interior tuples by index
tups = [(1,2,0),(2,9,6),(2,3,6)]
print([sum(x)/len(x) for x in zip(*tups)])
# [1.6666666666666667, 4.666666666666667, 4.0]
You can also do something like sum(x)//len(x) or round(sum(x)/len(x)) inside the list comprehension to get an integer.
Here are couple of ways you can do it.
data = [(1,2,0),(2,9,6),(2,3,6)]
avg_array = []
for tu in data:
avg_array.append(sum(tu)/len(tu))
print(avg_array)
using list comprehension
data = [(1,2,0),(2,9,6),(2,3,6)]
comp = [ sum(i)/len(i) for i in data]
print(comp)
Can be achieved by doing something like this.
Create an empty array. Loop through your current array and use the sum and len functions to calculate averages. Then append the average to your new array.
array = [(1,2,0),(2,9,6),(2,3,6)]
arraynew = []
for i in range(0,len(array)):
arraynew.append(sum(array[i]) / len(array[i]))
print arraynew
As you were told in the comments with sum and len it's pretty easy.
But in python I would do something like this, assuming you want to maintain decimal precision:
list = [(1, 2, 0), (2, 9, 6), (2, 3, 6)]
res = map(lambda l: round(float(sum(l)) / len(l), 2), list)
Output:
[1.0, 5.67, 3.67]
But as you said you wanted 3 ints in your question, would be like this:
res = map(lambda l: sum(l) / len(l), list)
Output:
[1, 5, 3]
Edit:
To sum the same index of each tuple, the most elegant method is the solution provided by #PatrickHaugh.
On the other hand, if you are not fond of list comprehensions and some built in functions as zip is, here's a little longer and less elegant version using a for loop:
arr = []
for i in range(0, len(list)):
arr.append(sum(l[i] for l in list) / len(list))
print(arr)
Output:
[1, 4, 4]
In a list, there might be several largest numbers. I want to get the indices of them all.
For example:
In the list a=[1,2,3,4,5,5,5]
The indices of the largest numbers are 4,5,6
I know the question is easy for most of people, but please be patient to answer my question.
Thanks :-)
In [156]: a=[1,2,3,4,5,5,5]
In [157]: m = max(a)
In [158]: [i for i,num in enumerate(a) if num==m]
Out[158]: [4, 5, 6]
1) create a variable maxNum = 0
2) loop through list if a[i] > maxNum : maxNum = a[i]
3)loop through list a second time now if a[i] == maxNum: print(i)
Try this:
a=[1,2,3,4,5,5,5]
b = max(a)
[x for x, y in enumerate(a) if y == b]
Use heapq:
import heapq
from operator import itemgetter
a=[1,2,3,4,5,5,5]
largest = heapq.nlargest(3, enumerate(a), key=itemgetter(1))
indices, _ = zip(*largest)
Of course, if your list is already sorted (your example list is), it may be as simple as doing
indices = range(len(a) - 3, len(a))
mylist=[1,2,3,3,3]
maxVal=max(mylist)
for i in range(0,len(mylist)):
if(mylist[i]==maxVal):
print i