Program to find permutation of a string - Error - python

Python Program
x=input("Enter any string:")
Taking input from user
z=len(x)*len(x)
y=len(x)-1
l,m=0,0
function to swap the values
def swap(s1,s2):
g=s1
s1=s2
s2=g
print(s1,s2)
return s1,s2
after swapping values to be printed in this for loop
for i in range(0,z,1):
s=x
swap(s[l],s[m+1])
print(s)
m=m+1
if m==y:
l=l+1
m=0
Code is not working properly but ending with the error IndexError: string index out of range

It might be the lack of brackets, for example, it might have to be:
if (m == y):

Related

how can i use multiple returned indices in a for loop to update a variable?

My question is: is there any way i can somehow use all the returned capital letter indices and replace them ALL with an underscore? I wished to take the returned values from the uppercase_finder function and insert an underscore in front of those capitalized letters. However, when I run the program, I only get the first capital letter of input with an underscore. Can I somehow iterate all the returned uppercase indices into the part where I insert underscores?
def main():
first_input = input("input here: ")
uppercase_indice = uppercase_finder(first_input)
new_case = first_input[:uppercase_indice] + "_" + first_input[uppercase_indice:]
new_case = new_case.lower()
print(new_case)
def uppercase_finder(x):
for i in range(len(x)):
if x[i].isupper():
return i
main()
Okay so based on the assumption that the overall goal is to print out the string inputted all lowercase and an underscore appended to each letter that was uppercase.
You could iterate through each letter in the string without focusing on the indices at all. Something like:
def main():
first_input = input("input here: ")
updated_input = ""
for letter in first_input:
if(letter.isupper()):
updated_input += "_" + letter.lower()
else:
updated_input += letter
print(updated_input)
Output:
input here: HeLLo
_he_l_lo
Generally though if you want to stick with the uppercase_finder function, the return statement in the loop stops the loop the moment any letter that is uppercase is found. In order to get all of the indices of each letter that is uppercase you would need something like this:
def uppercase_finder(x):
list_of_indices = []
for i in range(len(x)):
if x[i].isupper():
list_of_indices.append(i)
return list_of_indices
Then in the main function you can iterate across the list:
for index in uppercase_indice:
# Make string manipulations for each index
It's obviously an assignment problem so I'm not going to spoon-feed the answer. But I can point out what's the problem in your uppercase_finder.
The problem is that it is returning the index as soon as it find the first upper case. What you can do is
def uppercase_finder(x):
uppercase_indices = []
for i in range(len(x)):
if x[i].isupper():
# Append the index to the list uppercase_indices
return uppercase_indices
There's some problem with your uppercase_finder function, 'return' denotes the end of a function, whenever a return is met, the function will immediately stop and exit with an returned value. For ur case, it seems u wanna return all the indices where there are a capital letter, u may use yield instead of return thus making the function a generator.
def uppercase_finder(x):
for i in range(len(x)):
if x[i].isupper():
yield i
use the output of a generator via a loop:
for capital_pos in uppercase_finder(first_input):
do_sth

Issues with multiplication table output

I'm trying to print out the multiplication table and my function prints out one row at a time.
It works fine alone, but when I run multitable(n) through a for loop, it prints out "None" at the end of each row.
Why is this happening and how do I get rid of it?
def multitable(n):
for num in range (1,12+1):
print(num*n,end = " ")
#multitable(1)
#multitable(2)
for n in range (1,12+1):
print(multitable(n))
Replace this:
print(multitable(n))
with this:
multitable(n)
Your program is printing None because that's the value that multitable() is returning. If you don't want to see it, all you have to do is to avoid printing it.
mutlitable(n) does not return anything and thus returns None, which you then print. Seperate the statements.
def multitable(n):
for num in range (1,12+1):
print(num*n,end = " ")
#multitable(1)
#multitable(2)
for n in range (1,12+1):
multitable(n)
print()
It's the return value of the function, which you print out. If there is no return statement
https://docs.python.org/3/reference/simple_stmts.html#return
Like the accepted answer multitable(n) will do the needful, otherwise return the function
for n in range (1,4):
multitable(n)
print()

how to remove the runtime (NZEC) error in my python code?

I am trying to solve the prime generator problem PRIME1 in spoj.com but getting runtime error(NZEC). The problem needs to take a number of test cases and for each test case, it needs to input two numbers in a line for each different test case and then finally print the output as the prime numbers in the range of each number
The error is Runtime error time: 0.01 memory: 7736 signal:-1
# your code goes here
def is_prime(x):
if x<2:
return False
if x==2:
return True
for y in range(2,x):
if x%y==0:
return False
return True
t=int(raw_input())
mylist=[]
for i in range(0,t):
a=raw_input()
a=a.split(' ')
mylist.append(int(a[0]))
mylist.append(int(a[1]))
k=0
while k<len(mylist):
c=mylist[k]
k+=1
d=mylist[k]
k+=1
for z in range(c,d+1):
if is_prime(z):
print z
print
On running this on python 2.7.9, I found that there is only one error that you are using t in range(0, t) but t is string here, because our raw_input() method reads input and returns string. That raises in Python parlance. To remove this we should have to type cast the input we got. Like, t = int(raw_input()).
And this will result in t as an integer.
For info about raw_input() follow: https://docs.python.org/2/library/functions.html#raw_input
For reading integer in python you can follow this post on stackoverflow.
Your issue is raw_input() returns string , not integer. But you are trying to use it directly in your range() function - for i in range(0,t) . range() function only accepts integers as arguments, so you need to convert your input into int before using in range.
t=int(raw_input())

Implementing a function that sums integers contained in a string in Python

So I've recently picked up John Guttag's Introduction to Computation and Programming Using Python,the revised and expanded edition, after having worked through most of LPTHW. I am using the book in conjunction with MIT OCW 006. Now, I was trying to complete one of the Finger Exercises listed in the book, specifically the one of page 85, chapter 7, where the author asks you to implement a function using a try-except block:
def sumDigits(s):
"""Assumes s is a string
Returns the sum of the decimal digits in s
For example, if is is'a2b3c' it returns 5"""
This is my code:
def sumDigits(s):
try:
total = 0
list1 = [s]
new_list = [x for x in list1 if x.isdigit()]
for e in new_list:
total += new_list[e]
return total
except TypeError:
print "What you entered is not a string."
When I run this program in the IDLE using a test input, the total is always computed to be zero, indicating that none of the elements of new_list are being passed to the accumulator. Could someone suggest why that is? Thanks.
It seems like the errors have been pointed out already by Rafael but it is still important to note that the more pythonic way to approach this would be:
return sum([int(x) for x in s if x.isdigit()])
There are actually several errors with your code.
Let's break them down in detail
The main problem is located in these lines:
list1 = [s]
new_list = [x for x in list1 if x.isdigit()]
You should loop directly over the string first
new_list = [x for x in s if x.isdigit()] #s is the input string
When you create a new list as you did, the variable x in x for x in list1 will take place as elements of the list. So, in your case, the list will have only one element, which happen to be whole string (because you defined the list as [s]. As the whole string is not a digit, new_list will be an empty list.
That is why you are getting 0 as a return.
However, if you loop through the string directly, x will take place as each letter in the string, and then it will be possible to check whether x is digit or not.
It is also important to highlight that new_list[e] will raise IndexError. You should correct that for e only. The sintax of for e in new_list makes the local variable e assume each value inside the list, so you do not have to get the value via indexes: you can use e directly.
Finally, in order to sum the values in your new_list, the values should be integers (int) and not string (str), so you have to cast the values to int before summing (or, you can cast each element to int during the list comprehension, by using int(x) for x in s if x.isdigit() instead of x for x in s if x.isdigit()). Also, in order to check if the input is a string or not, you better use isinstance(s, basestring) if you're in python2, or isinstance(s, str) if you're using python3.
So the whole code would look like this :
def sumDigits(s):
if isinstance(s, basestring):
total = 0
new_list = [x for x in s if x.isdigit()]
for e in new_list:
total += int(e)
return total
else:
print "What you entered is not a string."
I'm working through the same book and the MITx: 6.00.1x course on edX; here's my solution:
def sumDigits(s):
'''
Assumes s is a string
Returns the sum of the decimal digits in s
For example, if s is 'a2b3c' it returns 5
'''
result = 0
try:
for i in range(len(s)):
if s[i].isdigit():
result += int(s[i])
return result
except:
print('Your input is not a string.')
Since we are to assume that s is a string, the except block should handle those cases where s is not a string. So simple, but it was not obvious to me at first.
You can use reduce method
reduce( (lambda x, y: x + y), [int(x) for x in new if x.isdigit()] )
I'm working through the same book too. I think we should use the try-except block on determining whether characters of string convertible to an integer. So here is my solution.
def sumDigits(s):
"""Assumes s is a string
Returns the sum of the decimal digits in s
For example, if s is 'a2b3c' it returns 5"""
sum = 0
for i in s:
try:
sum += int(i)
except ValueError:
None
return sum

Python 'for' function

I am trying to write a code that returns every prime palindrome with three digits. Here is my code:
def digpalprim():
for x in range (100,1000):
if prime(x)=='prime':
if str(x)==str(x)[::1]:
return x
I've already defined the prime(x) function, it works well, that stage just determines whether x is prime or not. All in all the code works, except that it only gives me the first such a palindrome. I don't really understand why, shouldn't the program consider all the numbers between 100 and 1000? Please help?
Your function returns as soon as it finds the first such palindrome; return exits a function.
Collect your finds in a list and return that:
def digpalprim():
palindromes = []
for x in range (100,1000):
if prime(x)=='prime':
if str(x)==str(x)[::1]:
palindromes.append(x)
return palindromes
or you can make your function a generator by replacing the return with a yield statement:
def digpalprim():
for x in range (100,1000):
if prime(x)=='prime':
if str(x)==str(x)[::1]:
yield x
Now you'll have to iterate over this function or use list() to 'pull' all values out:
all_palindromes(digpalprim())
or
for palindrome in digpalprim():
print(palindrome)
You are returning the function the first time you encounter one.
def digpalprim():
palprimes = []
for x in range (100,1000):
if prime(x)=='prime':
if str(x)==str(x)[::1]:
palprimes.append(x)
return palprimes
This creates a list at the start of the function and appends each valid palindrome prime to that list, then returns the entire list (after completing all loops) instead of returning just the first one encountered.
Just remember, if Python hits a return statement, it's going to stop function execution right there and return that value regardless of any additional loops or code you may intend to be executed.
The function returns and ends as soon as the first result is found.
You may wish to add the results to a list and then print out the list.
return x This statement causes the program to return to the calling function once this statement is encountered. To return all you may put it in an list. For e.g:
you can have a list called values and append it to it, and finally return it at the end
For such small tasks, I prefer using list comprehensions:
palindromes = [x for x in range(100, 1000) if (prime(x) == 'prime') and (str(x) == str(x)[::1])]
Or (equivalently):
condition = lambda f: prime(f) == 'prime' and str(f) == str(f)[::1]
palindromes = [x for x in range(100, 1000) if condition(x)]

Categories

Resources