create python list of exactly three elements - python-3.x

is it possible to create a list of exact 3 elements?
I wan to create an list (or may be tuple) for exact the elements (coordinates in 3-d).
I can do it as:
nhat=input("Enter coordinate\n")
the problem is that it will take any number (even greater or less then 3).
But it will be good if I have it prompting for number if it is <3 and exit when 3 value is given.
Edit
what I am currently doing is:
nhatx=input("Enter x-coordinate\n")
nhaty=input("Enter y-coordinate\n")
nhatz=input("Enter z-coordinate\n")
and then making the nhat list made of nhat{x,y,z}. Just thinking if I can define a list of predefined dimension, so that I don't need those nhat{x} variables

You could try something like:
def get_coords():
while True:
s = input("Enter coordinates (x y z): ")
try:
x, y, z = map(float, s.split())
except ValueError: # wrong number or can't be floats
print("Invalid input format.")
else:
return x, y, z
Now your code becomes:
nhatx, nhaty, nhatz = get_coords() # unpack tuple
or
nhat = get_coords() # leave coords in tuple

Related

Python3: comparing dynamic list to create a regexp

I am currently writing a class to create a regexp.
As an input, we got 3 sentences in a list ("textContent") and the output regexp should match the 3 sentences.
For this, I use ZIP. The code below is 100% working.
from array import *
textContent = []
textContent.append("The sun is.shining")
textContent.append("the Sun is ShininG")
textContent.append("the_sun_is_shining")
s = ""
for x, y, z in zip(textContent[0], textContent[1], textContent[2]):
if x == y == z:
s+=str(x)
else:
s+="."
#answer is ".he..un.is..hinin."
print(s)
It's working but ONLY with 3 sentences in a List.
Now, I want the same comparison but with a dynamic list that could contain 2 or 256 sentences for example. And I'm stuck. I don't know how to adjust the code for that.
I noticed that the following throws no error:
zip(*textContent)
So, I'm stuck with the variables that I compare before: x, y, z
for x, y, z in zip(*textContent):
It could work only if textContent contains 3 values...
Any idea? May be another class than ZIP could make the job.
Thanks
This will solve your problem with zipping and comparing:
l = ['asd', 'agd', 'add', 'abd']
for letters in list(zip(*l)):
if all([letters[0] == letter for letter in letters]):
print('Yey')
else:
print('Ugh')
>>> Yey
>>> Ugh
>>> Yey
And for l = ['asd', 'agg', 'add', 'cbb'] it will print 3 'Ugh'.
Also you should check if l is longer than 0

How can i optimise my code and make it readable?

The task is:
User enters a number, you take 1 number from the left, one from the right and sum it. Then you take the rest of this number and sum every digit in it. then you get two answers. You have to sort them from biggest to lowest and make them into a one solid number. I solved it, but i don't like how it looks like. i mean the task is pretty simple but my code looks like trash. Maybe i should use some more built-in functions and libraries. If so, could you please advise me some? Thank you
a = int(input())
b = [int(i) for i in str(a)]
closesum = 0
d = []
e = ""
farsum = b[0] + b[-1]
print(farsum)
b.pop(0)
b.pop(-1)
print(b)
for i in b:
closesum += i
print(closesum)
d.append(int(closesum))
d.append(int(farsum))
print(d)
for i in sorted(d, reverse = True):
e += str(i)
print(int(e))
input()
You can use reduce
from functools import reduce
a = [0,1,2,3,4,5,6,7,8,9]
print(reduce(lambda x, y: x + y, a))
# 45
and you can just pass in a shortened list instead of poping elements: b[1:-1]
The first two lines:
str_input = input() # input will always read strings
num_list = [int(i) for i in str_input]
the for loop at the end is useless and there is no need to sort only 2 elements. You can just use a simple if..else condition to print what you want.
You don't need a loop to sum a slice of a list. You can also use join to concatenate a list of strings without looping. This implementation converts to string before sorting (the result would be the same). You could convert to string after sorting using map(str,...)
farsum = b[0] + b[-1]
closesum = sum(b[1:-2])
"".join(sorted((str(farsum),str(closesum)),reverse=True))

comparing elements of a list from an *args

I have this function that I need to compare the strings in a list to a *args
The reason being is that, the user should be able to type any words in the 2nd argument. However when I try to compare the strings to the *args it doesn't give me any results
def title_case2(title, *minor_words):
for x in title.split():
if x in minor_words:
print(x)
Assuming I ran the function with the parameters below. I was hoping it would display a and of since these words are found on those 2 entries.
title_case2('a clash of KINGS','a an the of')
*args is a tuple of arguments, so you're actually checking if x is in ('a an the of',). So either pass your argument as:
title_case2('a clash of KINGS', *'a an the of'.split())
Or, use this as your test:
if any(x in y for y in minor_words):
In either of the above cases the output is:
a
of
This is one approach.
Ex:
def title_case2(title, *minor_words):
minor_words = [j for i in minor_words for j in i.split()] #Create a flat list.
for x in title.split():
if x in minor_words:
print(x)
title_case2('a clash of KINGS','a an the of', "Jam")
using a for-loop instead of list comprehension
def title_case2(title, *minor_words):
minor_words_r = []
for i in minor_words:
for j in i.split():
minor_words_r.append(j)
for x in title.split():
if x in minor_words_r:
print(x)

Python3 - Combine Dictionaries with existing key value pairs

So... I know we can combine 2 dictionaries from python 3.5 like so:
z = {**x,**y} # x,y are 2 similar dictionaries, with nested entries
But in this method, any conflicting key,value pairs in 'x' is replaced with the ones in 'y'.
I want the conflicting key,value pairs to contain largest data present in x or y.
For example:
x = {1:'small_data',2:{1:'random laaaarge data',2:'random small data'}}
y = {1:'laaaaaarge_data',2:{1:'random small data',2:'random laaaarge data'}}
Now
z = {**x,**y}
# DATA in z should be {1:'laaaaaarge_data',2:{1:'random laaaarge data',2:'random laaaarge data'}}
NOTE: It should work for any arbitrary data that has a size.
Is this even possible? If so, what is the most pythonic way to do it.
Why not something like:
def merge_dicts(dict_list):
merged = {}
for sub_dict in dict_list:
for key, value in sub_dict.items():
if key in merged:
merged[key] = get_biggest(merged[key], value)
else:
merged[key] = value
return merged
def get_biggest(*items):
# function for comparing your 2 items based on your "size" requirements
return biggest

Python 3.X: Implement returnGreater() function using a list of integers and a value

The function must return a list consisting of the numbers greater than the second number in the function
It must be able to do the following when functioning:
returnGreater([1,2,3,4,5], 3)
[4,5]
returnGreater([-8,2,-4,1,3,-5],3)
[]
Here's what I have (I've gone through a few iterations), though I get a Type Error for trying to use a ">" symbol between an int and list:
def returnGreater (x,y):
"x:list(int) , return:list(int)"
#greater: int
greater = []
for y in x:
#x: int
if x > y:
x = greater
return greater
You're using the name y for two different things in your code. It's both an argument (the number to compare against) and the loop variable. You should use a different name for one of those.
I'd strongly suggest picking meaningful names, as that will make it much clearer what each variable means, as well as making it much less likely you'll use the same name for two different things. For instance, here's how I'd name the variables (getting rid of both x and y):
def returnGreater(list_of_numbers, threshold):
greater = []
for item in list_of_numbers:
if item > threshold:
greater.append(item)
return greater
You had another issue with the line x = greater, which didn't do anything useful (it replaced the reference to the original list with a reference to the empty greater list. You should be appending the item you just compared to the greater list instead.
I recommend filter. Easy and Graceful way.
def returnGreater(x, y):
return list(filter(lambda a:a>y, x))
It means, filter each element a in list x using lambda whether a is greater than y or not.
List Comprehensions
def returnGreater(_list, value):
return [x for x in _list if x > value]

Resources