How-to Create A List From An Existant List - python-3.x

I'm having some issues with an exercise assignment on python:
I need to take a list of items, lets say lst = [1, 4, 37, 48, 7, 15], and create a function that would allow me to extract from this list all numbers that are divisible by one and/or by themselves, creating a new list of items.
lst = [1, 4, 37, 48, 7, 15], z is non negative.
def func(lst,z):
y = []
z > 0
for i in lst:
if (i % z == 0):
y.append(i)
return y
print(func(lst,z))
Output: [1, 4, 37, 48, 7, 15]
I get the same result list/result.

Well, isn't every number divisible by itself and 1? That is why your list is the same.
Setting z=4 yields [4,48], which is every number that is divisible by 1, itself, and 4.

Related

Return range of integer list based on input number

I found this question in my test today, I have been trying to find correct answer for this but failing to do so.
Question is:
Imagine we have range of page numbers lets say 0, 100. When we click on page lets say 15, we only what to show 10 pages on UI i.e. from page 10 to 20
more example input: 50 output: returns list
[46,47,48,49,50,51,52,53,54,55]
input: 15
output: returns list
[11,12,13,14,15,16,17,18,19,20]
also list should include first page and last page i.e. 0 and 50
so the actual output would be for first example
[0,46,47,48,49,50,51,52,53,54,55,100]
Below is what I have tried
def get_thread_page_num(num, max_page_num):
# Returns 10 numbers dynamically
new_lst =[1,50]
# default list
# defult_lst = [1,2,3,4,5,6,7,8,9,10]
num -4 > 0
num+5 <max_page_num
i = 10
m = 4
p = 5
while i != 0:
if num-1 >0 and m !=0:
new_lst.append(num-m)
i=i-1
m = m-1
elif num+1<max_page_num and p != 0:
new_lst.append(num+p)
i=i-1
p = p-1
print(sorted(new_lst))
get_thread_page_num(9, 50)
In your code m and p starts with value 4 and 5 respectively. In every iteration, either of them decreases by 1. So, after 9 iteration both of them are 0 and new_lst contains 9 elements. Also i becomes 10-9 = 1.
But i never becomes 0 and the loop becomes infinite.
You can try below code instead. Please refer to the comments.
def get_thread_page_num(num, max_page_num):
# low and high denotes the low and high end of the list
# where middle element is num
low = max(0, num - 4)
high = min(num + 5, max_page_num)
lst = []
if max_page_num < 9:
# 10 element list is not possible
return lst
# In case high is same as max, just make the list as
# high-9, high -8, ..., high
if high == max_page_num:
lst = list(range(max(0, high - 9), high + 1))
else:
# Just create a list starting from low like -
# low, low + 1, ..., low + 9
lst = list(range(low, low+10))
# Add 0 and max if not already present
if 0 not in lst:
lst.append(0)
if max_page_num not in lst:
lst.append(max_page_num)
# return sorted lst
return sorted(lst)
Call to get_thread_page_num():
print(get_thread_page_num(15, 50))
print(get_thread_page_num(0, 50))
print(get_thread_page_num(2, 50))
print(get_thread_page_num(50, 50))
print(get_thread_page_num(43, 50))
Output:
[0, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 50]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 50]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 50]
[0, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]
[0, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 50]

How to generate a list of random values excluding values in another list

I am using Python 3.6.3.
My code generates a random list of five values (type integer).
The values in this random list are compared to another list, which contains values to exclude from the generated list. That means, if a random number is mentioned in the excluded_numbers list, a redraw must be processed to obtain a new value.
Below is a simplified source code : (you can copy/paste, this code is running)
import numpy as np
import random
excluded_values = [1,2,3,4,5,6,15,18,30] # values to exclude from the random list
print ("draw_numbers to exclude ",excluded_values,"\n")
loops = 1
for ln in range (0,loops):
# Random list
z=[]
z=random.sample(range(1,30), 5) # no duplicates
z.sort()
print ("Draw numbers original list z ", z,"\n")
# Standard deviation draw_numbers
deviation = np.std(z)
deviation=float(deviation)
deviation= round (deviation,5)
print ("draw_numbers loop number ",ln," ", z, " standard deviation ", deviation,"\n")
control_list = []
for i in range (0,5):
draw_number = z[i]
draw_number = str(draw_number)
print ("Draw number z[",i,"] ",draw_number)
print ("Original random list z ",z)
if int(draw_number) in excluded_values:
print ("Present in excluded_values")
# trigger if draw_number must be excluded
draw_number= random.randint(1,50)
print ("------>>> REDRAW draw_number ", draw_number)
draw_number = int (draw_number)
control_list.append(draw_number)
print ("Control list ", control_list," Original list z ",z,"\n")
else:
draw_number = int (draw_number)
control_list.append(draw_number)
print ("Control list ", control_list," z ",z,"\n")
continue
z = control_list
continue
But a problem is still remaining.
When a redraw occcurs, the new draw number must be checked against excluded_values list, AND control_list, in order to get a final control_ list completely clean with no duplicates.
I did not find how to arrange this double process after trying many ways in my code; I missed maybe an argument or method, and I dont know how to manage this "circular" process.
Below is an example of running the code above:
draw_numbers to exclude [1, 2, 3, 4, 5, 6, 15, 18, 30]
Draw numbers original list z [4, 6, 9, 12, 18]
draw_numbers loop number 0 [4, 6, 9, 12, 18] standard deviation 4.91528
Draw number z[ 0 ] 4
Original random list z [4, 6, 9, 12, 18]
Present in excluded_values
------>>> REDRAW draw_number 45
Control list [45] Original list z [4, 6, 9, 12, 18]
Draw number z[ 1 ] 6
Original random list z [4, 6, 9, 12, 18]
Present in excluded_values
------>>> REDRAW draw_number 40
Control list [45, 40] Original list z [4, 6, 9, 12, 18]
Draw number z[ 2 ] 9
Original random list z [4, 6, 9, 12, 18]
Control list [45, 40, 9] z [4, 6, 9, 12, 18]
Draw number z[ 3 ] 12
Original random list z [4, 6, 9, 12, 18]
Control list [45, 40, 9, 12] z [4, 6, 9, 12, 18]
Draw number z[ 4 ] 18
Original random list z [4, 6, 9, 12, 18]
Present in excluded_values
------>>> REDRAW draw_number 14
Control list [45, 40, 9, 12, 14] Original list z [4, 6, 9, 12, 18]
Thank you for your help and your time.
Anyway, take care and stay safe # home.
Greetings from Paris, France :)
Following the comments, here is a simpler solution
from random import sample
k = 5
all_values = range(30)
excluded_values = [1,2,3,4,5,6,15,18,30]
k_sampled = sample(set(all_values) - set(excluded_values), k)
print(k_sampled) # --> [28, 10, 8, 11, 20]

List and Dictionary Output mismatch for the same Input in Python 3

I have the following function which makes use of a dictionary of cycle_times to generate lists and dictionaries containing elements whose values are greater than a certain threshold.
def anamolous_cycle_time_index_and_lengths(cycle_time_dict, anamoly_threshold):
for meter,cycle_time_list in cycle_time_dict.items():
anamoly_dict = {cycle_time_list.index(x):x for x in cycle_time_list if x > anamoly_threshold}
anamoly_list = [x for x in cycle_time_list if x > anamoly_threshold]
print(meter,len(anamoly_dict))
print([value for key,value in anamoly_dict.items()])
print(anamoly_list)
Suppose I give the inputs as
new_dict = {104:[2,3,4,5,6,7,3,2,5,6,7], 101:[2,45,4,2,5,2,34,2,5,6,7], 106:[2,23,4,5,65,7,3,23,5,6,7]}
anamoly_threshold = 3
The outputs I get are
104 4
[4, 5, 6, 7]
[4, 5, 6, 7, 5, 6, 7]
101 6
[45, 4, 5, 34, 6, 7]
[45, 4, 5, 34, 5, 6, 7]
106 6
[23, 4, 5, 65, 7, 6]
[23, 4, 5, 65, 7, 23, 5, 6, 7]
Shouldn't the list and dictionary give me the same output? I have run a comprehension for both data structures on the same data.
Your problem is the use of .index(x). This returns the index for the first occurrence of x. And since dictionary keys are unique, you will see only the first occurrence of duplicate elements in your dict comprehension.
There are several ways to overcome this problem. The easiest is to use enumerate:
anamoly_dict = {index: x for index, x in enumerate(cycle_time_list) if x > anamoly_threshold}
Now the output for both methods is the same.

finding primes in a list, then printing them

i have to generate primes for a project at school. heres the requirement: The Sieve of Eratosthenes is an elegant algorithm for finding all of the prime numbers up to some limit n. The basic idea is to first create a list of numbers from 2 to n. The first number is removed from the list, and announced as a prime number, and all multiples of the number up to n are removed from the list. This process continues until the list is empty. For example, if we wished to find all the primes up to 10, the list would originally contain [2, 3, 4, 5, 6, 7, 8, 9, 10]. The 2 is removed and announced to be prime. Then 4, 6, 8, and 10 are removed, since they are multiples of 2. That leaves [3, 5, 7, 9]. Repeating the process, 3 is announced as prime, and 9 is removed because it is a multiple of 9. That leaves [5, 7]. And so on. Write a program called generatePrimes.py that prompts the user for a number n and outputs all the primes less than or equal to n. im lost
This question is of terrible quality and doesn't really deserve an answer, but here is a function for the sieve being described:
def pSieve(limit):
flags = [True] * limit
flags[0] = flags[1] = False
primes = []
for index, flag in enumerate(flags):
if flag:
primes.append(index)
for n in range(index * index, limit, index):
flags[n] = False
return primes
and you can see that it produces the correct results:
>>> pSieve(10)
[2, 3, 5, 7]
>>> pSieve(100)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
def pSieve(n):
m = (n-1)
b = [True]*m
i,p,ps = 0,3,[2]
while p*p < n:
if b[i]:
ps.append(p)
j = 2*i*i + 6*i + 3
while j < m:
b[j] = False
j = j + 2*i + 3
i+=1; p+=2
while i < m:
if b[i]:
ps.append(p)
i+=1; p+=2
return ps

How to find all numbers in a list that are not part of a pair - using python 3

I am trying to write a python 3 function that finds all numbers in a list (unspecified length) that are not part of a pair.
For example, given the list [1, 2, 1, 3, 2], the function will return 3; and given the list [0, 1, 1, 7, 8, 3, 9, 3, 9], the function will return 0, 7, and 8.
Thanks for your help!
You can use the following function :
>>> def find(l):
... return (i for i in l if l.count(i)==1)
>>> l= [0, 1, 1, 7, 8, 3, 9, 3, 9]
>>> list(find(l))
[0, 7, 8]
This function will return a generator that is contain the elements in list which those count is equal to 1.
I can tell you how I would do it. What does it mean a "pair"?
You should say, find all the numbers repeated oddly in the array.
First plan: (more efficient!)
Sort the list and then a single loop through your list should be enough to find how many numbers of each there are inside and you can generate awhile another list that you will return.
Second plan (nicer in python, but also more expensive because of the number of evaluations though the hole list):
Try the solution of Kasra. 'count' function from 'list' type helps our code but not our efficiency. It counts the number of times that appears the value 'i' on the list 'l', obviously.
If the pair need to be "closed pair" I mean, if you have three 1 (ones), do you have one pair and one single 1? or do you have all the 1 paired? If the second one, the solution of Kasra is Ok. Else you should compare:
if l.count(i) % 2 == 1
This can be easily and efficiently done in 3 lines with collections.Counter.
from collections import Counter
def unpaired(numbers):
for key, count in Counter(numbers).items():
if count % 2:
yield key
print(list(unpaired([1, 2, 1, 3, 2])))
# [3]
print(list(unpaired([0, 1, 1, 7, 8, 3, 9, 3, 9])))
# [0, 7, 8]
My answer comport if you have three equals numbers or if you have one pair and one single number without pair.
def name(array):
o = sorted(array)
c = []
d = []
for i in o:
if o.count(i) % 2 == 1:
c.append(i)
for j in c:
if j not in d:
d.append(j)
return d
or do not use for j in c and use directly:
return list(set(c))
for example:
array = [0, 1, 1, 7, 8, 3, 9, 3, 9, 9]
output: [0, 7, 8, 9]

Resources