def anti_vowel(t):
v = "aeiouAEIOU"
g = ""
for i in t:
for c in v:
if i == c:
g = g + i
print(g)
anti_vowel("umbrella")
o/p : uea
Why am I getting the o/p with only vowels but i wanted to do the exact opposite?
To make your code work, you can either switch to using in, or use a for-else statement and break if you do have a vowel match:
def anti_vowel(t):
v = "aeiouAEIOU"
g = ""
for i in t:
for c in v:
if i == c:
break
else:
g += i
return g
which does now give the intended output! :)
If you were after something slightly more efficient, you could use a generator with str.join:
def anti_vowel(t):
v = "aeiouAEIOU"
return ''.join(c for c in t if c not in v)
which we can see works:
>>> anti_vowel("umbrella")
'mbrll'
Note that using in is faster than a for-loop as the operation is much more optimised at the low-level. It also produces much more readable (or Pythonic) code.
Oh and btw I believe functions should always have an output - even if the intention is to print that output, so I have used returns instead.
Try this.
def anti_vowel(t):
v = "aeiouAEIOU"
r=[t]
[r.append(r[-1].replace(l,'')) for l in v]
return r[-1]
Related
I am a new Python learner. I am trying to finding the greatest common divisor of two numbers (a =1071 and b = 462 for example). I have written two programs for this. the first one is working but the second one gives the wrong answer. what is the problem with my program??
# first program (works)
a, b = 1071, 462
while b:
a, b = b, a % b
print(a)
# second program (doesn't work truly)
a = 1071
b = 462
while b:
a = b
b = a % b
print(a)
Explanation:
Yes, HSK is right. In the 2nd loop:
while b:
a = b
b = a % b
print(a)
First a is changed to b and then what you do is b = b% b. But here:
a, b = b, a % b
it is executed as one-line so a is still a.
Solution:
So just add a third variable:
a = 1071
b = 462
while b:
c = a
a = b
b = c % b
print(c)
One thing that distinguishes Python from other programming languages is that it is interpreted rather than compiled. This means that it is executed line by line.
The second doesn't work because, for the calculation of b, you need to use the old a, not the new a that got generated on the line before (this is actually set to b so you will get b % b, which will generally be zero). The equivalent to the first loop would be:
while b:
oldA = a
a = b
b = oldA % b
print(a)
The tuple assignment in Python can be considered an atomic operation where all the values on the right side are loaded up, then assigned to all the variables on the left side.
def divisor(n):
if n ==1 or n ==2 or n ==3:
return []
else:
result=[]
aux=2
while aux <= n:
if n % aux == 0:
result.append(aux)
aux=aux+1
return result
def func (m,n):
div1=divisor(m)
div2=divisor(n)
result =[]
for x in div1:
for y in div2:
if x == y:
result.append(x)
return result
print(func (x,y))
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))
I have a simple for loop iterating through a user input string. If the it encounters a certain value, I want to be able to look ahead at the next value in order to determine what to do next. What is the best way to accomplish this? For example in my code below, if it encounters a "1" in the string, it should look at the next character in the string. If it is also a 1, print 1. Otherwise do nothing.
UserInput = input("Enter calculator expression:")
for x in UserInput:
...
...
if x == 1:
# if the next value in the string is 1:
# print 1
# else:
# do nothing
Use range and len in the loop to get position address
UserInput = input("Enter calculator expression")
for i in range(len(UserInput)-1):
if x[i]=='1':
if x[i+1]=='1':
print "something"
else:
pass
You can zip a string with itself, but offset with a slice.
>>> from itertools import zip_longest
>>> the_input = 'foobar' # example
>>> the_input[1:] # slice off the first character
'oobar'
>>> for c, lookahead in zip_longest(the_input, the_input[1:]):
... print(c, lookahead)
...
f o
o o
o b
b a
a r
r None
This is more Pythonic than using an index like you would in a language like C.
Zipping pairs things elementwise, like the teeth of a zipper.
You can user enumerate() function.
something like this,
#!/user/bin/python3
for i,x in enumerate(UserInput):
if x=='1':
if UserInput[i+1] == '1':
print('1')
Firstly, python convention is snake-case (user_input instead)
code below is my solution
from itertools import islice
def window(seq, n=2):
it = iter(seq)
result = tuple(islice(it, n))
if len(result) == n:
yield result
for elem in it:
result = result[1:] + (elem,)
yield result
pair = list(window(user_input))
comparison_list = ["1"]
result = [x for x,y in pair if x in comparison_list and x == y]
You don't need to look ahead. At least it is not what we usually do when we tackle this kind of problem. Instead, you should look backward - by storing the information. The following example stores the information in a variable state and you can decide the next action in the subsequent iteration.
UserInput = input("Enter calculator expression:")
state = '0'
for x in UserInput:
if x == '1':
if state == '1':
print('1')
else:
state = '1'
else:
state = '0'
A different (probably more pythonic) way of doing this with the zip function:
for char, next_char in zip(UserInput, UserInput[1:]):
if char == "1" and char == next_char:
print(1)
prev_char = None
for char in input("Enter calculator expression:"):
pass # Here you can check the current character and the previous character
if 1 == prev_char and 1 == char:
print(1)
prev_char = char
I want to know if the code I wrote can be shortened further, I was practicing and I came up to a task which asks you to return a boolean value, this is what the question says:
Given two strings, return True if either of the strings appears at the
very end of the other string, ignoring upper/lower case differences
(in other words, the computation should not be "case sensitive").
Note: s.lower() returns the lowercase version of a string.
def end_other(a, b):
x = len(b)
n = a[-x:]
y = len(a)
m = b[-y:]
if b.lower() == n.lower() or a.lower() == m.lower() :
return True
else:
return False
The Code is working properly but I wondered if it can be shortened more so it looks good.
You can write it like this:
def end_other(a, b):
n = a[-len(b):]
m = b[-len(a):]
return b.lower() == n.lower() or a.lower == m.lower()
I removed variables x and y because they are used just one time and then I also remove the if-else statement because it's unnecessary, in fact you can just return the result of the comparison instead of checking it's result and returning it a second time.
def repeated(m, result, a, s, d):
check = True
r = 0
while r <= s - 1:
if result == m - 1:
check = False
return check
result = (result ** 2) % m
r = r + 1
return check
I need to write a primality testing python program to test very large numbers, like at least 100-digit numbers. The code above is part of the code for Miller Rabin deterministic primality test for repeated squaring. It works really slow for large numbers. How can I speed it up? It is for a project. Thanks!
your problem is probably the (result ** 2) % m, use the 3 argument version of pow that do the same but more efficiently because the algorithm use is the Modular exponentiation and that is much better than first doing x**n and then calculate its modulo. this way you are guaranty to never have a number bigger than m while if you do (x**n) % m you can have that x**n is very much bigger than m that may be the cause your problems
Also no need for the check variable and you don't use a.
Also as you go from 0 to s-1, better use range
def repeated(m, result, s, d):
for r in range(s):
if result == m - 1:
return False
result = pow(result, 2, m )
return True
Now for this part of the test
if
you need a, d, s, and n this is how I would do it
def mr_check(n,a,s,d):
result = pow(a,d,n)
if result == 1 :
return False
for r in range(s):
result = pow(result,2,n)
if result == n-1:
return False
return True