List being cleared when used Python - python

I have been using Python 2.7 for a couple of weeks and need some help on the loop below:
nos_rounds = raw_input("Number of rounds?")
student = stu_input(ui)# links to a function to input a list of strings
for x in range(0,int(nos_rounds)):
student2 = randomList(student)#randomising list function
student2 = partition(student,gs)#partitions the randomised list
fcprint(student2)#prints the student list to the console and a file
The problem I am having is the second time the loop runs the list 'student' is cleared out and made in to an empty list. 'student' is not altered at all by the code. What is going on here? I am new to coding and can't seem to work this out. Any help would be much appreciated!
functions requested are:
def randomList(a): # this creates a random list of students on the course
import random
b = []
for i in range(len(a)):
element = random.choice(a)
a.remove(element)
b.append(element)
return b
def partition(lst, n): # this creates sub list of the student list containing the groups of students
increment = len(lst) / float(n)
last = 0
i = 1
results = []
while last < len(lst):
idx = int(round(increment * i))
results.append(lst[last:idx])
last = idx
i += 1
return results
def fcprint(student):#print to the console and then to an external file
floc = raw_input("Input the name of the file")
f = open(floc +".doc", "w")
for item in range (0,len(student)):
print ""
print "Group",item+1, ":\n", "\n".join(student[item])
print >>f, "\n"
print >>f,"Group: ", item+1
print >>f, "\n".join(student[item])
f.close()
Thanks, I tried the below:
for x in range(0,int(nos_rounds)):
newstu = student[:]
print "top", newstu
student2 = randomList(newstu)# randomises the student list student is reconised on the first run but is empty on second run
print "bottom", newstu
student2 = partition(student2,gs)# creates the groups
fcprint(student)#prints the student list to the console and a file
Still can't get it to work. Output is for print statements:
top ['1', '2', '3', '4', '5']
bottom []
Got this to work with the excellent advice of the forum . Working version is:
def randomList(z): # this creates a random list of students on the course
import random
r = z[:]
b = []
for i in range(len(r)):
element = random.choice(r)
r.remove(element)
b.append(element)
return b
for x in range(0,int(nos_rounds)):
student2 = randomList(student)# randomises the student list student is reconised on the first run but is empty on second run
student2 = partition(student2,gs)# creates the groups
fcprint(student2)#prints the student list to the console and a file

The problem is at randomList():
def randomList(a): # this creates a random list of students on the course
import random
b = []
for i in range(len(a)):
element = random.choice(a)
a.remove(element)
b.append(element)
return b
At this line a.remove(element) you remove elements from the original list until it's gone. So on 2nd iteration it will be empty.
By #loutre: Try doing a copy of your list (e.g a_copy = a[:] and work with this copy inside the function

Related

I have a defined a variable inside a for loop, but when printing it outside of the loop it doesn't print correctly

Here is the code:
count_1 = 0
count_0 = 0
list = ('001111011011','000110001010','011010111111')`
for i in list:
index = 0
y = i[index]
if y == "1":
count_1 = count_1 + 1
if y == "0":
count_0 = count_0 + 1
if count_1 > count_0:
for i in list:
final_after_1 = []
if i[0] == "1":
final_after_1.append(i)
formatted = (','.join(final_after_1))
if count_0 > count_1:
for i in list:
final_after_1 = []
if i[0] == "0":
final_after_1.append(i)
formatted = (','.join(final_after_1))
if count_0 == count_1:
for i in list:
final_after_1 = []
if i[0] == "1":
final_after_1.append(i)
print(final_after_1)
formatted = (','.join(final_after_1))
print(formatted)
(Apologies in advance if this question is worded badly, this is my first time asking a question).
This piece of code is working fine except for this one issue. It is designed to identify the first index of each 12-digit number in the list, and then work out if a 1 or 0 is more common in this position. It then selects all the numbers with the more common number in the first position and adds them to a list. I want to print this list at the end of the program.
I have defined a variable (called formatted) to be equal to a list of various numbers. When I print it out within the loop I have defined it in, it prints all the numbers that should be in the list, like this:
When I print it outside of the loop as in the code above it returns only the final number:
011010111111
Whereas printing it inside the loop like this:
if count_0 > count_1:
for i in list:
final_after_1 = []
if i[0] == "0":
final_after_1.append(i)
formatted = (','.join(final_after_1))
print(formatted)
does return this full desired list:
001111011011
000110001010
011010111111
Any ideas why this is happening?
Within you loop(s) the value of formatted is updated for each iteration. After the last iteration it is no longer updated and that last value is the output of the last print statement.
A simpler example:
for x in range(100):
pass//looping over, x is 0..99
print(x)
This will print out 99, the last value held by the variable "x".
Problably your code is updateing the variable for each iteration so in a for loop you need to append the values and not overwrite them, for example:
a = 0
b = 0
for i in 10:
a = 1
b = b + 1 # using the last value
print(a) # 1
print(b) # 9
First of all you shouldn't use "list" as a variable name because is a built-in name to instanciate lists or arrays. In second your code is repeated 3 times just for count a bit, let me show a better way with list compreenssions:
l = ('001111011011','000110001010','011010111111')
first_elements = list()
for x in l:
v = x[0] # first element
first_elements.append(int(v))
# [0,0,0]
count_0 = first_elements.count(0)
# count_0 = 3
count_1 = first_elements.count(1)
# count_1 = 0
Using list compreenssion
first_elements = [int(x[0]) for x in l]
# [0,0,0]
References: list compreenssions, list, list.count

How to add the digits in a number and place the result in a list

(sorry for bad title I had trouble sumerizing)So I'm working on a project where a have to take a list of completely random numbers, find the sum of digits in each number, and place that sum in a list. Here is what I have so far:
import random
import math
list1 = [random.randint(1,1000000000000) for i in range(0,10)]
list2 = []
list3 = []
def open_command():
for y in range(0,10):
a = list1[y]
z = len(str(a))
for x in range(0, z):
f = len(str(a))
b = a*0.1
c, w=(math.modf(b))
d = int(c*10)
list2.append(d)
a = (a - d)/10
if f == 0:
total = sum(list2)
list3.append(total)
list2.clear()
open_command()
print(list3)
When I run this code the list3 just displays an empty list however there is no error. I don't understand, Is the .append not working? Can somebody explain what is going on?
Using map, One liner
list_num = [123,456]
print([sum(list(map(int, list(str(num))))) for num in list_num])
Output:
[6, 15]
That comes because the following code never got executed. List 3 is never appended and the list 2 never gots clear.
if f == 0:
total = sum(list2)
list3.append(total)
list2.clear()
You never change a, so the length of it (f) never becomes 0. Therefore, you never append anything.
But you're overcomplicating things:
list3 = [sum(int(char) for char in str(num)) for num in list1]
Or, if you want to keep your basic concept:
def open_command():
for number in list1:
for char in str(number):
list2.append(int(char))
list3.append(sum(list2))
list2.clear()
return list3

How can I change the order of 2d list in python

I am working on cut up method in python. Where I am breaking the text of text file in columns. I want to change the order of the elements, meaning if text is sbreaking into column A, B and C, I want to now display the text in column A, C and B. My program is as following
import sys
def first(aList):
for row in colList:
for item in row:
print(item, end=" ")
print()
ncolumns = int(input("Enter Number of Columns:"))
file = open("alice.txt", "r")
rowL= []
colList= []
print(" ")
print(" ")
print("++++++++++++++++++++++++++++++++++++++")
while True:
line = file.readline()
if not line:
break
numElements = len(line.rstrip())
_block= numElements//ncolumns
block = _block
start=0
rowL =[]
for count in range(0,(ncolumns)):
columnChars = ""
for index in range(start,block):
columnChars += line[index]
rowL.append(columnChars)
start = block
block = block + _block
if (block < numElements):
if((block + _block)>numElements):
block = numElements
colList.append(rowL)
file.close()
first(colList)
Just create a new list indexing the elements from the old list.
That is to say,
old_list = [1, 2, 3]
new_list = [old_list[0], old_list[2], old_list[1]]
which would give new_list as [0, 3, 2].
You use slice assignment here.
lst= [0,1,2]
lst[1:]=lst[1:][::-1]
print(lst)
# [0, 2, 1]
Take a look at How slicing as assignment works if you don't get it.

How can I take a list and append each element to a new list depending on its position?

So my first list created via a for loop looks like the following
["1variable1", "1variable2", "1variable3", "1variable4", "1variable5"].
I then want it to be appened to new list depending on their position.
so List1 will be [1variable1]
List2 will be [1variable2]
etc
Then the next step of the loop will create another
["2variable1", "2variable2", "2variable3", "2variable4", "2variable5"]
I then want to append that to the previous list to make;
List1 will be [1variable1, 1variable2]
List2 will be [1variable2, 2variable2]
etc.
At the moment I have it so that it simply used square brackets to pull out each part of the list but I don't know how to get this in a loop, maybe next time I run it there will be more than 4 entries and I will miss the 5th.
lst1 = [item[0] for item in Genres]
lst2 = [i[1] if len(i) > 1 else '' for i in Genres]
lst3 = [i[2] if len(i) > 2 else '' for i in Genres]
lst4 = [i[3] if len(i) > 3 else '' for i in Genres]
lst5 = [i[4] if len(i) > 4 else '' for i in Genres]
If the next list doesn't have as many as a previous list then it should fill in a blank space as they all need to be in the same position
The lists are created as follows;
my_list = my_list[1:]
length = len(my_list)
my_list = my_list[0:3]
for film in my_list:
filmIndex = my_list.index(film) + 1
query = film + " imdb"
for j in search(query, tld="co.in", num=10, stop=1, pause=2):
page = requests.get(j)
response = page.status_code
if response == 200:
soup = BeautifulSoup(page.content, "lxml")
genreData = soup.find_all("div",{"class":"subtext"})
Then
for h in genreData:
a = h.find_all('a')
aLength = len(a)
a1 = a[0]
for b in range(0,aLength - 1):
r = a[b].string
genres.append(r)
I then want to add each genre into a seperate column, genre1, genre2 etc. up to how ever many max is. Obviously some of these mull be NULL if the max is 4 and one film only has 1
Then for each film will create a list of all the genres for that film and I want to put them into separate columns
One possible method is to create a list of lists.
Creating a list of lists lets you iterate through the list to insert and place each variable into the list at the variable's index. Of course, if you've got a big list or are doing your first pass, you'll hit an index you haven't encountered yet, so you'll need to init an empty list at that index.
list1 = ["1variable1", "1variable2", "1variable3", "1variable4", "1variable5"]
list2 = ["2variable1", "2variable2", "2variable3", "2variable4", "2variable5"]
biglist = []
#insert list1
#this for loop can be repeated for every list you want to enter - maybe
#put those into a list of lists, too?
for i in range(0, len(list1)):
#check to see if there's a list in this entry
if 0 <= i < len(biglist):
#there's already a list here, add this to it
biglist[i].append(list1[i])
else:
#there's no list here yet, create one and add its first variable
biglist.append([])
biglist[i].append(list1[i])
#repeat for the second list, and so on - you can nest these
for i in range(0, len(list2)):
if 0 <= i < len(biglist):
biglist[i].append(list2[i])
else:
biglist.append([])
biglist[i].append(list2[i])
for l in biglist:
print(l)
Demo

Python - replay values in list

Please help for task with the list in Python my logic is bad works:( .
This is full text of task: Write a program that takes a list of
numbers on one line and displays the values in a single row, are
repeated in it more than once.
To solve the problem can be useful sort method list.
The procedure for withdrawal of repetitive elements may be arbitrary.
My beginning code is :
st = (int(i) for i in input().split())
ls = []
for k in st:
if k == k + 1 and k > 1:
Task is : if we have replay value in list we must print it. We only can use sort() method and without any modules importing.
Results Examples:
Sample Input 1:
4 8 0 3 4 2 0 3
Sample Output 1:
0 3 4
Sample Input 2:
10
Sample Output 2:
Sample Input 3:
1 1 2 2 3 3
Sample Output 3:
1 2 3
This code isn't run( sort() function doesn't want sort my_list. But I must input values like my_list = (int(k) for k in input().split())
st = list(int(k) for k in input())
st.sort()
for i in range(0,len(st)-1):
if st[i] == st[i+1]:
print(str(st[i]), end=" ")
my_list = (int(k) for k in input().split())
After running this line, my_list is a generator, something that will create a sequence - but hasn't yet done so. You can't sort a generator. You either need to use []:
my_list = [int(k) for k in input().split()]
my_list.sort()
which makes my_list into a list from the start, instead of a generator, or:
my_list = list(int(k) for k in input().split()))
my_list.sort()
gather up the results from the generator using list() and then store it in my_list.
Edit: for single digits all together, e.g. 48304, try [int(k) for k in input()]. You can't usefully do this with split().
Edit: for printing the results too many times: make the top of the loop look backwards a number, like this, so if it gets to the second or third number of a repeating number, it skips over and continues on around the loop and doesn't print anything.
for i in range(0,len(st)-1):
if st[i] == st[i-1]:
continue
if st[i] == st[i+1]:
print...
st = (int(i) for i in input().split())
used = []
ls = []
for k in st:
if k in used: # If the number has shown up before:
if k not in used: ls.append(k) # Add the number to the repeats list if it isn't already there
else:
used.append(k) # Add the number to our used list
print ' '.join(ls)
In summary, this method uses two lists at once. One keeps track of numbers that have already shown up, and one keeps track of second-timers. At the end the program prints out the second-timers.
I'd probably make a set to keep track of what you've seen, and start appending to a list to keep track of the repeats.
lst = [num for num in input("prompt ").split()]
s = set()
repeats = []
for num in lst:
if num in s and num not in repeats:
repeats.append(num)
s.add(num)
print ' '.join(map(str,repeats))
Note that if you don't need to maintain order in your output, this is faster:
lst = [num for num in input("prompt ").split()]
s = set()
repeats = set()
for num in lst:
if num in s:
repeats.add(num)
s.add(num)
print ' '.join(map(str, repeats))
Although if you can use imports, there's a couple cool ways to do it.
# Canonically...
from collections import Counter
' '.join([num for num,count in Counter(input().split()).items() if count>1])
# or...
from itertools import groupby
' '.join([num for num,group in groupby(sorted(input().split())) if len(list(group))>1])
# or even...
from itertools import tee
lst = sorted(input('prompt ').split())
cur, nxt = tee(lst)
next(nxt) # consumes the first element, putting it one ahead.
' '.join({cur for (cur,nxt) in zip(cur,nxt) if cur==nxt})
this gives the answers you're looking for, not sure if it's exactly the intended algorithm:
st = (int(i) for i in input().split())
st = [i for i in st]
st.sort()
previous = None
for current in st:
if ((previous is None and current <= 1)
or (previous is not None and current == previous + 1)):
print(current, end=' ')
previous = current
>>> "4 8 0 3 4 2 0 3"
0 3 4
>>> "10"
>>> "1 1 2 2 3 3"
1 2 3
updated to:
start with st = (int(i) for i in input().split())
use only sort method, no other functions or methods... except print (Python3 syntax)
does that fit the rules?

Categories

Resources