I'm new to Python and programming in general so maybe there is a simple way to do this without much hassle. The code I've written so far is this (I'm giving you all the code for context):
def prime(n):
if n > 1:
for i in range(2, n):
if n % i == 0:
return False
return True
def length(n):
if len(n) > 5:
return True
return False
def list_filter(lista):
return [x for x in lista if x]
toggle = False
enter_numbers = True
zero_one_neg = True
prime_list = []
lcm_list = []
while enter_numbers:
nums = list(map(int, input('\nEnter up to five natural numbers greater than 1 separated by commas. Enter at least two if you want to calculate their LCM: ').split(',')))
for i in range(len(nums)):
if nums[i] <= 1:
zero_one_neg = True
print('\nNo zeroes, ones or negatives. Start over. ')
if length(nums) and zero_one_neg:
print('\nNo more than five numbers. Start over. ')
break
break
else:
zero_one_neg = False
if length(nums) and not zero_one_neg:
print('\nNo more than five numbers. Start over. ')
elif not length(nums) and not zero_one_neg:
enter_numbers = False
for i in range(len(nums)):
lcm_list.append([])
prime_list.append([])
for j in range(2, nums[i]):
if nums[i] % j == 0:
lcm_list[i].append(j)
if prime(j):
prime_list[i].append(j)
toggle = True
if not toggle:
print('\n', nums[i], 'is a prime number.')
if toggle:
print('\n', nums[i], 'is not a prime number. It\'s prime factors are: ', prime_list[i])
toggle = False
filtered_lcm_list = list_filter(lcm_list)
filtered_prime_list = list_filter(prime_list)
for i in range(len(filtered_lcm_list)):
l = list(map(int, filtered_lcm_list[i]))
print(l)
print(filtered_lcm_list)
The problem is in this section:
for i in range(len(filtered_lcm_list)):
full_list = list(map(int, filtered_lcm_list[i]))
print(full_list)
print(filtered_lcm_list)
If i give an input of say 88,77 i get this output:
Enter up to five natural numbers greater than 1 separated by commas. Enter at least two if you want to calculate their LCM: 88,77
88 is not a prime number. It's prime factors are: [2, 11]
77 is not a prime number. It's prime factors are: [7, 11]
[7, 11]
[[2, 4, 8, 11, 22, 44], [7, 11]]
Process finished with exit code 0
I want full_list
to contain all the elements of filtered_lcm_list
but not as a list of lists.
How about this?
full_list = [int(i) for sub_list in filtered_lcm_list for i in sub_list]
This makes use of a list comprehension, first iterating over the lists contained in filtered_lcm_list
, then over the elements in each of those nested lists.
If you don't want duplicate numbers returned, you could use a set comprehension:
full_list = {int(i) for sub_list in filtered_lcm_list for i in sub_list]}
and convert that back to a list, using list(full_list)
if you wish.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.