How turn my loop results into a list - python

I have no idea how to use put these results into a list and sort it using python3.
def get_new(x):
i = 0
while i < 6:
i = i+1
print (x)
x = (x*31334)%31337
get_new(7546)

One way to do this is to create a list and append the values of x. Then return this list from your function:
def get_new(x):
lst = []
i = 0
while i < 6:
i = i+1
x = (x*31334)%31337
lst.append(x)
return lst
print (get_new(7546))
#[8699, 5240, 15617, 15823, 15205, 17059]

For calculating and sorting the calculated list, do this using list append and sort.
def get_new(x):
new_list = []
i = 0
while i < 6:
i = i+1
#print (x)
x = (x*31334)%31337
new_list.append(x) # append the each new value of x to `new_list`
return new_list
a = get_new(7546) # returns the unsorted calculated list
a.sort() # sorting using sort() function
print (a)
#OUTPUT [5240, 8699, 15205, 15617, 15823, 17059]

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

Even values from lists into a set

Here is the given assignment + code:
Write a function even_value_set(list1, list2, list3), which receives
three lists containing integer items as arguments. The function
creates and returns a set that contains all items with even value from
all three lists.
def test():
l = [[],[],[]]
for i in range(3):
for j in range(random.randint(7,14)):
l[i].append(random.randint(1,35))
print ("List" + str(i + 1) +":",l[i])
print ("")
s = even_value_set(l[0],l[1],l[2])
print ("Return type:", str(type(s)).replace("<","").replace(">",""))
print ("Set with even values only:", end = "")
print (set(sorted(list(s))))
test()
import random
I tried using .union() and making adding lists into another before turning them into sets, but didn't have any luck.
You can do this in a simply pythonic way. This function can be written as a simple oneliner using comprehension
def even_value_set(list1, list2, list3):
return set([num for num in list1+list2+list3 if num % 2 == 0])
Basically, what we did here is concatenated all lists, fitered even numbers and then made it into a set.
You can union lists (with duplicates) with the + operation.
union_list = list1 + list2 + list3
If you only want the unique values you can call set on this list.
unique_set = set(union_list)
Now you can create a new empty set and iterate over the unqiue_set and add all the even values:
solution = set()
for v in unique_set:
if v%2==0:
solution.add(v)
def even_value_set(*lsts):
s = set()
for lst in lsts:
s |= {x for x in lst if x % 2 == 0}
return s
Also you can use starring
def even_value_set(*lsts):
return set().union(*[{x for x in lst if x % 2 == 0} for lst in lsts])
And solution with concatenation (more memory).
set comprehension is more effective than set()
def even_value_set(l1, l2, l3):
return {x for x in l1+l2+l3 if x % 2 == 0}
You can make the union of lists using +, like list1 + list2. Then just walk through the result list checking if the number is even and adding in another list.
def even_value_set(list):
result = set()
for val in list:
if val%2 == 0:
result.add(val)
return result
def test():
l = [[],[],[]]
for i in range(3):
for j in range(random.randint(7,14)):
l[i].append(random.randint(1,35))
print ("List" + str(i + 1) +":",l[i])
print ("")
uni = l[0] + l[1] + l[2]
s = even_value_set(uni)
print ("Return type:", str(type(s)).replace("<","").replace(">",""))
print ("Set with even values only:", end = "")
print (set(sorted(list(s))))
test()
import random
Is it what you want? I think your question is confusing.

How to separate Consecutive and Non consecutive number from a python list

Input:
lst = [101,102,103,104,120,131,132,133,134]
Expected output:
consecutive - [101,102,103,104,131,132,133,134]
non consecutive = [120]
def first_consecutive(lst):
a = []
for i,j in enumerate(lst,lst[0]):
if i!=j:
a.append(j)
return a
Any suggestion?
You can just keep a list as you loop through the (sorted) numbers. When you encounter something that's consecutive, add it to the list. Otherwise put the values in the right place and redefine the list. Easier to show than explain:
l = [101,102,103,104, 120,131,132,133,134]
def partition_groups(l):
out = [[], []]
current = [l[0]]
for n in l[1:]:
if current[-1] + 1 == n:
current.append(n)
else:
out[len(current) > 1].extend(current)
current = [n]
out[len(current) > 1].extend(current)
return out
nonconsecutive, consecutive = partition_groups(l)
print(nonconsecutive)
# [120]
print(consecutive)
# [101, 102, 103, 104, 131, 132, 133, 134]
You could do something like this
def sort_list(list):
sorted_list = []
non_consecutive_list = []
for i in range(len(list)):
if list[i] + 1 in list or list[i] - 1 in list:
sorted_list.append(list[i])
else:
non_consecutive_list.append(list[i])
return sorted_list, non_consecutive_list
num_list = [101,102,103,104,120,131,132,133,134]
sorted_list, non_consecutive_list = sort_list(num_list)
print(sorted_list, non_consecutive_list)
This? (assumes list is already sorted, if not just call lst.sort() first)
(Simply compare each element to its previous (if any) and next (if any) neighbour.)
consec = []
non_consec = []
L = len(lst)
for i in range(L):
if i>0 and lst[i-1]==lst[i]-1 or i<L-1 and lst[i+1]==lst[i]+1:
consec.append(lst[i])
else:
non_consec.append(lst[i])

Why can a function be usable in determined range?

I've been learning Python since a while and developing a function for doing a list of Lucky numbers i made this code:
def lucky(n):
list = []
rem1 = []
rem2 = []
# First verification
for i in range(1,n+1,2):
list.append(i)
print (list)
# Second verification
for i in range(2,m,3):
element = list[i]
rem1.append(element)
list = [x for x in list if x not in rem1]
# Third verification
n=(len(list))+1
for i in range(6,n,7):
element = list[i]
rem2.append(element)
list = [x for x in list if x not in rem2]
return list
My problems begins when running values bigger than 55. Why can Python take as out of range the code after that specific number and how could it be corrected?
The word "list" is a reserved word in python, you should change the name to a non-reserved word.
You have a type on line 16: for i in range(2,m,3): that "m" should be an "n", should it not?
The range you use in your second for loop exceeds the length of the list object. You need to check the length with an if statement.
for i in range(2,n,3):
if len(my_list) > i:
element = my_list[i]
rem1.append(element)
Reading in a math web, i found this problem.
It is solved with this code:
def lucky(n):
# Lista inicial
lista = list(range(1, n + 1, 2))
# Variable inicial
indice = 1
# Ciclo de ejecuciĆ³n
while indice <= len(lista) - 1 and lista[indice] <= len(lista):
lista = [Li for i, Li in enumerate(lista) if (i + 1) % lista[indice]]
indice += 1
# Resultados
return lista
My question here is about how is line 8 working

how to change values in an list and create a new list

Code:
a = [4,4,6,4,10]
for i in a:
if i == 4:
i = i + 10
print(i)
I want this code to form a new array, which is:
b = [14,14,6,14,10]
I don't understand how to do it.
Break it down in to parts. Right now you are actually properly checking for a number that equals to 4 and incrementing it by 10, which is great.
You are right now missing two key components:
Creating a new list and appending to it
An else condition for all the other elements that you want.
So, for the first part, start by creating a new list:
new_list = []
So, we have:
a = [4,4,6,4,10]
new_list = []
Then, you want to append to your new list:
for i in a:
if i == 4:
i = i + 10
new_list.append(i)
However, now, you need to accommodate for the values you do not want to increment, this is where you need an else condition:
So, if it does not equal to 4, simply append the value as is to your new list:
for i in a:
if i == 4:
i = i + 10
new_list.append(i)
else:
new_list.append(i)
That pretty much corrects the problems you had in your code.
Now, one small adjustment to make, is that this line:
i = i + 10
Can be re-written as: i += 10
So, finally, we have:
a = [4,4,6,4,10]
new_list = []
for i in a:
if i == 4:
i += 10
new_list.append(i)
else:
new_list.append(i)
Finally, this can all be shortened in to one line as:
new_list = [i + 10 if i == 4 else i for i in a]
for idx in range(len(a)):
i = a[idx]
if i == 4:
i = i+10
a[idx] = i
It can be easily done with a list comprehension:
>>> a = [4,4,6,4,10]
>>> b = [14 if x == 4 else x for x in a]
>>> b
[14, 14, 6, 14, 10]
or alternatively, closer to your original code:
[i + 10 if i == 4 else i for i in a]
The problem with your code is that the line
i = i + 10
does not modify the values of the list. All you do is rebind the name i to i + 10 - but then you do nothing with the new value.
The traditional way, without a list comprehension, would look like this:
>>> a = [4,4,6,4,10]
>>> b = [] # empty result list
>>> for item in a:
... if item == 4:
... b.append(14) # alternatively: b.append(item + 10)
... else:
... b.append(item)
...
>>> b
[14, 14, 6, 14, 10]

Categories

Resources