Python3: comparing dynamic list to create a regexp - python-3.x

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

Related

why doesn't this regex (\d)\d\1 work to find alternate repetitive numbers from a string?

I have to write regex to find all the repetitive alternate numbers from a given string.
For example:
552523
(5,5)and(2,2) are the pairs
My basic understanding of regex is not very good.
From what I understand the expression (\d)\d\1 should give 525 and 252 but it only returns 5 while using re.findall function in python.
Why doesn't this work? And is there a good way to accomplish this?
You can perform the overlapping match by using the lookahead assertion.
Would you please try the following:
import re
str = "552523"
m = re.finditer(r'(?=((\d)\d\2))', str)
for i in m:
print(i.group(1))
Output:
525
252
Another way to come at it would be to zip over the string and a slice of the string offset by 2 looking for matching digits in the resulting tuples.
Example:
digit_string = "552523"
digit_pairs = [
(x, y)
for x, y in zip(digit_string, digit_string[2:])
if x.isdigit() and y.isdigit() and x == y
]
print(digit_pairs)
Output:
[('5', '5'), ('2', '2')]

ValueError: invalid literal for int() after reading input into a tuple

I am writing a code that takes some numbers as tuple and then verify if there are numbers divisible by 3.
I am a beginner in python and just know some basic stuff about tuples. I have my code below:
def Div3and5():
data=tuple(input("Enter 3 numbers:"))
c=[]
a=0
for i in range(0,len(data)):
d=data[i]
c.append(d)
m=[int(x) for x in c]
print(m)
for i in m:
if m[i]%3==0:
print("It is not divisible")
Div3and5()
So, when I run this code I get an error which is:
ValueError: invalid literal for int() with base 10: ','
See, the values are stored as integers and when I give a command of printing c, it clearly shows all elements. Then, I try to convert each element to integers but it says error I don't know why. So, can you tell me the reason for that error. And also is there any straight-way for using this (divisibility) operation directly on tuples without converting them to list first.
Thanks
You are likely entering the numbers with spaces (or commas) in between. Hence, these spaces (or commas) make it into the tuple -- and can't be converted into ints.
Try instead, using str.split() to put the input numbers into a list.
def Div3and5():
c = input("Enter 3 numbers:").split(",")
# Gives you the list e.g. ["3", "4", "5"]
m = [int(x) for x in c]
# Gives you the list e.g. [3, 4, 5]
for i in m:
if i % 3 == 0:
print(f"{i} is divisible by 3")
Div3and5()
Remember that str.split() will accept a delimiter as an argument. In this case, I've put a comma ,, but you can have a space ' ' instead, depending on how your input should be entered by the user.
Note also, you were doing if m[i] % 3 == 0 in the if statement instead of if i % 3 == 0. This is not correct since i in each iteration of the loop is an element of the list m, and not an index.
Also, your condition i % 3 == 0 is such that if i is divisible by 3, then the print should indicate that the number is divisible -- you were printing that it's not divisible (probably a typo).
If you want all the numbers divisible by 3 and 5, you can change the condition like this:
if i % 3 == 0 and i % 5 == 0:
print(f"{i} is divisible by 3 and 5")
Here is the answer of your QUESTION :
def Div3and5():
c = input("Enter 3 numbers:")
list=c.split(",")
c=tuple(list)
m = [int(x) for x in c]
for i in m:
if i % 3 == 0:
print(f'{i} is is divisible by 3')
Div3and5()
#Enter 3 numbers with "," : 123,45,67

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))

How can i convert many variable to int in one line

I started to learn Python a few days ago.
I know that I can convert variables into int, such as x = int (x)
but when I have 5 variables, for example, is there a better way to convert these variables in one line? In my code, I have 2 variables, but what if I have 5 or more variables to convert, I think there is a way
You for help
(Sorry for my English)
x,y=input().split()
y=int(y)
x=int(x)
print(x+y)
You could use something like this .
a,b,c,d=[ int(i) for i in input().split()]
Check this small example.
>>> values = [int(x) for x in input().split()]
1 2 3 4 5
>>> values
[1, 2, 3, 4, 5]
>>> values[0]
1
>>> values[1]
2
>>> values[2]
3
>>> values[3]
4
>>> values[4]
5
You have to enter value separated with spaces. Then it convert to integer and save into list. As a beginner you won't understand what the List Comprehensions is. This is what documentation mention about it.
List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
So the extracted version of [int(x) for x in input().split()] is similar to below function,
>>> values = []
>>> input_values = input().split()
1 2 3 4 5
>>> for val in input_values:
... values.append(int(val))
...
>>> values
[1, 2, 3, 4, 5]
You don't need to create multiple variables to save your values, as this example all the values are saved in values list. So you can access the first element by values[0] (0th element is the first value). When the number of input values are large, let's say 100, you have to create 100 variables to save it. But you can access 100th value by values[99].
This will work with any number of values:
# Split the input and convert each value to int
valuesAsInt = [int(x) for x in input().split()]
# Print the sum of those values
print(sum(valuesAsInt))
The first line is a list comprehension, which is a handy way to map each value in a list to another value. Here you're mapping each string x to int(x), leaving you with a list of integers.
In the second line, sum() sums the whole array, simple as that.
There is one easy way of converting multiple variables into integer in python:
right, left, top, bottom = int(right), int(left), int(top), int(bottom)
You could use the map function.
x, y = map(int, input().split())
print x + y
if the input was:
1 2
the output would be:
3
You could also use tuple unpacking:
x, y = input().split()
x, y = int(x), int(y)
I hope this helped you, have a nice day!

create python list of exactly three elements

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

Resources