Related
I want to create five random list but have same and not repeat number from 1-100.
I only know I can remove the number from a list which have all number I want and chose randomly put in to new list:
All_list is a list I save all the list I want to save random number from 1-100
number_list is the list including all number I want but it isn't random
number_list = list(range(1, 101))
for i in range(5):
All_list.append(list)
for a in range(1,101):
random_num = random.choice(number_list)
All_list[i-1].append(random_num)
number_list.remove(random_num)
But in:
All_list[i-1].append(random_num)
The above gives a typeError: descriptor 'append' for 'list' objects doesn't apply to a 'int' object. Why does this happen?
Can anyone help me rewrite this code? I will be appreciative about it.
The quick fix is, when calling All_list.append, to pass an empty list ([]), instead of the class list.
The error message is hard to understand without knowing some details about how methods work. Since All_list contains the class list, the following statement:
All_list[i-1].append(random_num)
is equivalent to:
list.append(random_num)
This grabs the append function from the list class and calls it in a way that treats random_num as the object instead of a list. Python sees that random_num is not an instance of the class where append is defined, so it throws an error.
Of course, you still have another error caused by the inner loop using up all of number_list. I don't know exactly what you're trying to do there.
Create list of random number, and group the random number into chunk_size size sublist.
import random
data = random.sample(range(1,101), 100)
chunk_size=int(len(data)/5)
_chunks=list(data [i:i+chunk_size]
for i in range(0, len(data ), chunk_size))
Output
[[98, 91, 87, 92, 85, 45, 3, 1, 76, 13, 11, 14, 43, 21, 42, 73, 26, 61, 63, 79], [12, 29, 2, 48, 10, 70, 30, 81, 44, 83, 49, 20, 24, 54, 77, 23, 40, 66, 32, 51], [31, 55, 9, 8, 60, 72, 19, 38, 57, 27, 68, 53, 41, 56, 35, 75, 17, 7, 64, 90], [33, 52, 71, 39, 62, 94, 16, 93, 37, 4, 99, 34, 65, 36, 58, 6, 82, 97, 88, 5], [86, 84, 78, 50, 18, 89, 59, 46, 100, 15, 47, 95, 74, 22, 67, 25, 69, 28, 80, 96]]
Your code on line 3 is where the problem is, All_list.append(list). I guess you meant to append number_list in All_list.
Hi #Peggy Lin and Welcome to Stack Overflow.
The error which you mentioned is due to the append function being used with an element of the list which is an integer unless you meant All_list to be a nested list.
Note:
You Should provide a minimal-reproducible-example along with a clear statement regarding what exactly is the problem with your code and also a clear sample output which you intend to get from the corrected code. Refer this to better your question
Please clarify the following points in your problem statement to get better and useful answers:
What type of a list do you require? A nested list containing 5 lists with their random numbers as their elements OR 5 seperate lists with each having random elements as their elements?
but have same and not repeat number from 1-100
Clarify what you meant by this.
I only know I can remove the number from a list which have all number I want and chose randomly put in to new list
This seems to indicate that either you already have a list OR You want to generate the list then modify it. Clarify the statement.
What purpose does number_list serve? What elements do you need in it?
Hope these will guide you in improving your question!
I am fairly new to python, and was trying to make my own bubble sort recursively. While error testing, i changed the code to this:
from sys import setrecursionlimit
setrecursionlimit(10000)
def bubbleSort(arr):
for index in range (len(arr)-1):
if arr[index] > arr[index+1]:
arr[index], arr[index+1] = arr[index+1], arr[index]
return bubbleSort(arr)
array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
array.reverse()
print(array)
sorted_array = bubbleSort(array)
print(array)
This initially prints a list from 99-0, and then after sorting, reverses the list, as is the idea of this algorithm. I just have no idea why this still works despite the fact that I assigned the sorted list to a new variable, printed the old variable, and it still prints a sorted list. In addition to this, I don't understand why the function doesn't return NoneType having finished sorting. Basically, my algorithm works, but I have no idea why. Can anyone help?
Just to help you understand how list works in Python.
Python call by reference or call by value
Python utilizes a system, which is known as “Call by Object Reference” or “Call by assignment”. In the event that you pass arguments like whole numbers, strings or tuples to a function, the passing is like call-by-value because you can not change the value of the immutable objects being passed to the function. Whereas passing mutable objects can be considered as call by reference because when their values are changed inside the function, then it will also be reflected outside the function.
Example 1:
# Python code to demonstrate
# call by value
string = "Geeks"
def test(string):
string = "GeeksforGeeks"
print("Inside Function:", string)
# Driver's code
test(string)
print("Outside Function:", string)
output-1
Inside Function: GeeksforGeeks
Outside Function: Geeks
Example 2
# Python code to demonstrate
# call by reference
def add_more(list):
list.append(50)
print("Inside Function", list)
# Driver's code
mylist = [10,20,30,40]
add_more(mylist)
print("Outside Function:", mylist)
Output-2
Inside Function [10, 20, 30, 40, 50]
Outside Function: [10, 20, 30, 40, 50]
I have the task where I need to find number of columns similar to the first one. I have certain array of MxN size, where numbers within the range of 0 to 100. Firstly, I want to try to solve it with static array (without pseudo random numbers), but I'm stuck and cannot find a solution. So far I have this:
firstCol = []
temp = []
amount = 0
table = [[36, 36, 78, 36, 38, 41],
[65, 6, 23, 65, 49, 89],
[18, 70, 77, 18, 59, 0],
[53, 46, 80, 66, 10, 13],
[33, 93, 26, 57, 37, 23],
[83, 37, 39, 27, 53, 100],
[1, 11, 46, 96, 98, 93],
[54, 33, 90, 88, 83, 58]]
firstCol = [e1[0] for e1 in table]
theSame = [False] *10
n=1
temp = [e2[n] for e2 in table]
The rest of the code doesnt work, so I didn't write it here. The idea is to compare values offirstCol` and temp arrays. Values of temp will change every loop. If there is a better idea how to do that I would be happy to see it, thanks in advance =)
If my reputation score was high enough, I would comment and say "This looks a bit like a homework assignment." I would then try to provide you with some guidance as to how to move forward, like I might suggest you research how to iterate through an array.
But since I can only answer questions, I'll provide you with code that accomplishes your goal ( I think ). Hope this helps:
# Lets create a vector/array for our results and initalize it to zero
counts=[0] * len(table)
# step through the two dimensional array...
for index,row in enumerate(table):
# The first column is index 0 of the row
firstValue = row[0]
# Now just compare the firstValue to the rest of the values in the row
for colValue in row[1:]:
if colValue == firstValue:
counts[index] = counts[index] + 1
print counts
How I can convert each item in a list into tuples after they were appended to that list? I have this list:
Cards = []
I want to append 100 cards to the Card list without having to do this:
Card = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,...]
So I did this instead:
for i in range(1, 101):
Cards.append(i)
print(Cards)
And that gave me the result I was looking for which was:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
Now, I want to convert each number into a tuple, I tried multiple things:
tuple(Cards)
and:
Cards = []
x = "()"
for i in range(1, 101):
Cards.append(i)
x.join(Cards)
But none of them gave me:
[(1), (2), (3), (4),...]
How can I make ^ happen?
Try a list comprehension for fast and pythonic list of single element tuples:
Cards = [(i,) for i in range(1, 101)]
Sample session:
>>> Cards = [(i,) for i in range(1, 101)]
>>> Cards
[(1,), (2,), (3,), (4,), (5,), (6,), (7,), (8,), (9,), (10,), (11,), (12,), (13,), (14,), (15,), (16,), (17,), (18,), (19,), (20,), (21,), (22,), (23,), (24,), (25,), (26,), (27,), (28,), (29,), (30,), (31,), (32,), (33,), (34,), (35,), (36,), (37,), (38,), (39,), (40,), (41,), (42,), (43,), (44,), (45,), (46,), (47,), (48,), (49,), (50,), (51,), (52,), (53,), (54,), (55,), (56,), (57,), (58,), (59,), (60,), (61,), (62,), (63,), (64,), (65,), (66,), (67,), (68,), (69,), (70,), (71,), (72,), (73,), (74,), (75,), (76,), (77,), (78,), (79,), (80,), (81,), (82,), (83,), (84,), (85,), (86,), (87,), (88,), (89,), (90,), (91,), (92,), (93,), (94,), (95,), (96,), (97,), (98,), (99,), (100,)]
In case one does not want to display the required comma, one could:
>>> for c in Cards: print '(%s),' % c[0],
...
(1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11), (12), (13), (14), (15), (16), (17), (18), (19), (20), (21), (22), (23), (24), (25), (26), (27), (28), (29), (30), (31), (32), (33), (34), (35), (36), (37), (38), (39), (40), (41), (42), (43), (44), (45), (46), (47), (48), (49), (50), (51), (52), (53), (54), (55), (56), (57), (58), (59), (60), (61), (62), (63), (64), (65), (66), (67), (68), (69), (70), (71), (72), (73), (74), (75), (76), (77), (78), (79), (80), (81), (82), (83), (84), (85), (86), (87), (88), (89), (90), (91), (92), (93), (94), (95), (96), (97), (98), (99), (100),
But this is only display. The comma is necessary for a single element tuple literal to distinguish it from the "grouping" parentheses that allow you ege to write longer strings without an exploding right margin like so:
long_string = ("foobarbaz foobarbaz"
" yes")
will result in long_string content:
"foobarbaz foobarbaz yes"
Try this:
Cards = []
for i in range(1, 101):
Cards.append((i,))
Note that a tuple is usually 2 items, so when you print the array there will be an extra comma. Might be better to use a 1 dimensional array instead, ie:
Cards.append([i])
I have a problem writing the following arrays to a .txt file.
This is my code:
for i in range(len(my_particles)):
list = []
list.append(my_particles[i].n)
for z in range(len(my_particles[i].neighbours)):
list.append(my_particles[i].neighbours[z])
#for i in range(len(list)):
print >>f, list
f.close()
This is the output:
[0, 2, 20, 91, 114, 127]
[1, 6, 24, 114]
[2, 0, 65, 73, 91, 114]
[3, 71, 91, 120]
[4, 16, 69, 104]
[6, 1, 25, 87, 100, 114]
[7, 19, 83, 111]
[9, 38, 59, 72, 76]
[11, 56, 101, 108]
[12, 86, 92, 126]
[13, 30, 79, 82, 101, 104]
[14, 78, 103, 124]
[15, 23, 44, 90, 116]
[16, 4, 97, 106, 108]
[17, 19, 85, 111]
[18, 47, 60, 68, 74]
Is there a way to print it in this format?
0, 2, 20, 91, 114, 127
1, 6, 24, 114
I have tried
print>>f, "".join(list)
But it does not work, as it is a list of numpy64 floats.
You want to make strings out of each member of the list first. Try
print >>f, ', '.join(map(str,list))
Also, don't name variables list!
Try
",".join(str(i) for i in list))
hacky fix:
print(str(list).replace(']','').replace('[',''))
Converting them to strings should work
print >>f, ', '.join(str(elem) for elem in my_list)
and as Brien said, don't call your list list
If list is a numpy array of floats:
list.astype('str')
OR-You can also use csv to write np.arrays quickly:
import csv
import numpy as np
a = np.random.uniform(0,10,size = (5,5))
writer = csv.writer(open('txtfile.txt','wb'))
writer.writerows(a)
Yields txt file:
3.55183065126,1.05649949199,5.15510365109,1.0369928554,7.66646909667
9.5145737219,1.53877245296,5.53917128683,1.55343228883,8.78227048275
5.80408228776,2.58788175555,0.502704494319,1.63833152952,3.59898531148
2.94430872526,2.42069917781,5.75920106752,2.42453222446,1.73308148034
1.9579612159,0.609573767011,3.87717828624,7.86853109668,7.41038950637
or if you wanted integers, adding:
writer.writerows(a.astype(int))
would yield
2,0,3,4,1
9,5,4,4,3
9,7,6,4,2
3,5,7,2,0
6,0,2,7,7
Firstly, you should use the with statement when dealing with files to ensure they are automatically closed even if the program encounters an error befor they finish. Secondly, you can replace for i in range(len(my_list)) and my_list[i] with for i in my_list and i. Also, having a variable called list overwrites the inbuilt type list. Common practice is to use a trailing underscore to avoid this.
This code should work (although I don't currently have Numpy installed to test it with)
with open("myfilename.txt","w") as f:
for i in my_particles:
list_ = []
list_.append(i.n)
for j in value.neighbours:
list_.append(j)
f.write(", ".join(str(n) for n in list_))
Note that this will erase the previous contents of the file. If you don't want this, open the file with "a" in the open function rather than "w".