returning a list from multiple mixed args - python-3.x

I'm trying to write a function that accepts a list of numbers either as a single number or a range, the expected input syntax will be: 1,2 ,3-5, 7,9 -4
The function will be returning a list of string 'numbers'.
So this will be: '1','2','3','4','5','7','9','8','7','6','5','4'. Spaces should be removed.
which will have duplicates removed: '1','2','3','4','5','7','9','8','6'.
It would be nice to have these ordered ascending, but optional
Method
My first issue seems to be accepting 3-5 as a string, it is automatically returned as -2 so this needs to be identified and sent to list(map(str, range(3, 5))) [plus 1 to the highest number since it's python] this range can then be added to the listl.
Any single numbers can be appended to the list.
Duplicates are removed (solved).
The list is returned.
My outline
def get_list(*args):
# input 1-10,567,32, 45-78 # comes in as numbers, but should be treated as string
l=[] # new empty list
n=str(args) # get the args as a string
# if there is a '-' between 2 numbers get the range
# perhaps convert the list to a np.array() then loop through?
# I will need n.split(',') somewhere?
l = list(map(str, range(3, 5)))
# if just a single number append to list
l.append()
# remove duplicates from list
def remove_list_duplicates(l):
return list(dict.fromkeys(l))
l = remove_list_duplicates(l)
return l

Here's my solution for your problem:
ranges = input()
ranges = ranges.split(',') # i split the user input on ',' as i expect the user to specify the arguments with a ',' else you can split it on ' '(space)
def get_list(*ranges):
return_list = [] # initialize an empty list
for i in ranges:
try: # as these are strings and we need to process these exceptions may occur useexception handling
return_list.append(int(i)) # add the number to the list directly if it can be converted to an integer
except:
num_1,num_2 = map(int,i.split('-')) # otherwise get the two numbers for the range and extend the range to the list
if(num_1 > num_2):
return_list.extend([j for j in range(num_2,num_1 + 1 ,1)])
else:
return_list.extend([j for j in range(num_1,num_2 + 1 ,1)])
return list(set(return_list)) # to return a sorted and without duplicates list use the set method
print(get_list(*ranges)) # you need to use the spread operator as the split method on input returns a list
Ouptput:

Related

Is there a way to test if two separate values, in two separate arrays, and check if they are equal or not?

Im trying to see if a value in one array is equal to that in another array, the values are integer values.
Ive tried turning them into string and integers from the array but get the error that they cannot be converted implicitly.
winningnumber = []
usernumber = []
print(winningnumber)
print(usernumber)
if(winningnumber == usernumber):
print("Exact number")
I would then get an output like so
[1]
['1']
In order to do this, what you want to do is access the first item of each array, and compare that value.
There are a lot of ways to do this, but here is a little driver program to show you one way.
# Defining a function to see if they match
def is_winning(arr1, arr2):
# Grabbing the first element in each array
# denoted by the [0], for the "0th" element
arr1_first_ele = arr1[0]
arr2_first_ele = arr2[0]
# If the first element in the first array matches the first element in the second
if arr1_first_ele == arr2_first_ele:
# Print out they match
print("They match")
# Otherwise
else:
# Print out that they dont
print("They don't match")
def main():
# Example arrays
test_array_one = [1,3,4]
test_array_two = [5,4,3]
# This should print out "They don't match"
is_winning(test_array_one, test_array_two)
# Example arrays
test_array_three = [6,7,8]
test_array_four = [6,5,4]
# This should print out "They match"
is_winning(test_array_three, test_array_four)
main()
This evaluates to:
They don't match
They match

I am not able to understand the code. Can any one help me out?

marks = {}
for _ in range(int(input())):
line = input().split()
marks[line[0]] = list(map(float, line[1:]))
print('%.2f' %(sum(marks[input()])/3))
I am new to python. Can you tell me the meaning of this code?
I'm not able to understand it.
What this code does:
# initialized a dictionary type names marks
marks = {}
# The input() method will pause and wait for someone to input data in the command line
# The range() method will create an array of int given the a number
# example: range(5) will create [0, 1, 2, 3, 4]
# In this case it will take the string returned from input() convert it to an integer
# and use that as the value.
# The for loop will, run as many times as there are elements "in" the array created
# the _ is just a silly variable name the developer used because
# he is not using the value in the array anywhere.
for _ in range(int(input())):
# Get a new input from the user
# split the string (it uses spaces to cut the string into an array)
# example if you type "one two three" it will create ["one", "two", "three"]
# store the array in the variable line
line = input().split()
# add/replace the element using the first string in the line as key
# line[0] is the first element in the array
# lint[1:] is the array containing all the elements starting at index 1 (the second element)
# map() is a function that will call the function float on each elements of the array given. basically building an array with the values [float(line[1]), float(line[2])…]
# list will convert the array into a list.
marks[line[0]] = list(map(float, line[1:]))
# this last line asks the user for one more value
# gets the list in the marks dictionary using the value inputed by the user
# calculates the sum of all the floats in that list.
# divides it by 3 and prints the results as a floating point number with 2 decimal places.
print('%.2f' %(sum(marks[input()])/3))

Function that removes zeroes from list?

I just need a function that removes zeroes from an input list
def no_zero(a):
pos=0
while (pos+1)<=len(a):
if a[pos] == "0":
a.remove[pos]
pos= pos +1
return a
print(no_zero([0,1,0,2,0,3]))
I should be getting an output of 1,2,3 but instead it skips right to return a. Any pointers as to why? Cheers.
You can use a list comprehension:
def no_zero(a):
return [x for x in a if x != 0]
print(no_zero([0,1,0,2,0,3]))
Additionally, the reason your code currently isn't working is because you are comparing the items to a string ("0") instead of an integer (0). You are also attempting to modify a list as you iterate over it, which means that your indices don't correspond to the original indices of the list, and your result will be wrong.

merging some entries in a python list based on length of items

I have a list of about 20-30 items [strings].
I'm able to print them out in my program just fine - but I'd like to save some space, and merge items that are shorter...
So basically, if I have 2 consecutive items that the combined lengths are less than 30, I want to join those to items as a single entry in the list - with a / between them
I'm not coming up with a simple way of doing this.
I don't care if I do it in the same list, or make a new list of items... it's all happening inside 1 function...
You need to loop through the list and keep joining items till they satisfy your requirement (size 30). Then add them to a new list when an element grows that big.
l=[] # your new list
buff=yourList[0] if len(yourList)>0 else "" # hold strings till they reach desired length
for i in range(1,len(yourList)):
# check if concatenating will exceed the size or not
t=yourList[i]
if (len(buff) + len(t) + 1) <= 30:
buff+="/"+t
else:
l.append(buff)
buff=t
l.append(buff) # since last element is yet to be inserted
You can extend method of list as follows:
a = [1,2,3]
b = [4,5,6]
a.append('/')
a.extend(b)
You just need to check the size of two list a and b as per your requirements.
I hope I understood your problem !
This code worked for me, you can check to see if that's what you wanted, it's a bit lenghty but it works.
list1 = yourListOfElements
for elem in list1:
try: # Needs try/except otherwise last iteration would throw an indexerror
listaAUX = [] # Auxiliar list to check length and join smaller elements. You can probably eliminate this using list slicing
listaAUX.append(elem)
listaAUX.append(list1[list1.index(elem)+1])
if len(listaAUX[0]) + len(listaAUX[1]) < 30:
concatenated = '/'.join(listaAUX)
print(concatenated)
else:
print(elem)
except IndexError:
print(elem)

python3 string to variable

I am currently trying to implement Conway's Game of Life in a Code, and therefore built a function which generates the coordinates depending of the size of the window.
def coords_maker(num_x, num_y):
num_x += 1
num_y += 1
coords = []
for i in range (0,num_y, 1):
for n in range (0,num_x,1):
coords.append ('x'+str(n)+'y'+str(i))
return coords
Yet, I would like to randomly assign values to the resulting strings, to mark them either as alive (1) or dead (0). However they only way to convert a string to a variable name known to me is via a dict and var(), but however, it is essential for the further code that the coordinates stay sorted, as I want to be able to iterate over the ordered items and put the cursor accordingly to the coordinates name. Something like:
print ('\033['+X_COORD+';'+Y_COORD+'f'+ x1y5)
if e.g. x1y5 is the corresponding value (0 or 1) of the variable
Is there a convenient method how to either do this via a dict or how to convert the name of the strings to variable names?
Or probably. If I keep one dict and one list and store the coordinate names in the list and the values in the dict?
Thank you in advance!
kyril
You use a dictionary:
def coords_maker(num_x, num_y):
num_x += 1
num_y += 1
coords = {}
for i in range (0,num_y, 1):
for n in range (0,num_x,1):
coords['x'+str(n)+'y'+str(i)] = 0
return coords
You then access the value with
coords[x][y]
And change it like so:
coords[x][y] = 1
Now, of course this converting of coordinates to strings is completely pointless. Simply use a list of lists:
def coords_maker(num_x, num_y):
num_x += 1
num_y += 1
coords = [[0]*num_x for x in range(num_y)]
return coords
And I don't know why you add 1 to the coordinates either:
def coords_maker(num_x, num_y):
return [[0]*num_x for x in range(num_y)]

Resources