This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
How can I use `return` to get back multiple values from a loop? Can I put them in a list?
(2 answers)
Closed 5 days ago.
For example, if we run 5678 through the function, 25364964 will come out. So I wrote a code like this.
number = 5678
for ch in str(number):
print (int(ch)**2, end="")
And got the correct output.
25364964
However, if I put this code under a function, the expected result isn't showing up.
def square_every_number(number):
for ch in str(number):
return ((int(ch)**2))
print(square_every_number(5678))
Output:
25
I'm getting only the square for the first digit.
You are returning on the first loop. You should build up your result and return that.
def square_every_number(number):
res = ''
for ch in str(number):
res = res + str(int(ch)**2)
return res
Or a shorter function:
def square_every_number(number):
return ''.join(str(int(ch)**2) for ch in str(number))
You were returning after squaring the first character, please try squaring every character and form the resultant number in your function and return the final result as below.
def sq_every_num(number):
result = ''
for ch in str(number):
result += str(int(ch) ** 2)
return int(result)
output:
result = sq_every_num(5678)
print result, type(result)
25364964 < type 'int'>
Related
This question already has answers here:
How to convert numbers to words without using num2word library?
(24 answers)
How do I tell Python to convert integers into words
(17 answers)
Closed 15 days ago.
I have a game in python, and I wanted to print numbers. however, 1,000,000 doesn't really look as nice. I was wondering if there was a way I could automatically convert numbers like that into numbers like 1 million.
I tried setting up this code to detect the length of a number and to change it respectivly:
def replacer(s, newstring, index, nofail=False):
if not nofail and index not in range(len(s)):
raise ValueError("index outside given string")
if index < 0: # add it to the beginning
return newstring + s
if index > len(s): # add it to the end
return s + newstring
return s[:index] + newstring + s[index + 1:]
def numr(num):
if len(num) == 1:
pass
if len(num) == 2:
pass
if len(num) == 3:
replacer(num, " hundred", 2)
However, when I ran the code, it ourputted this:
None
Any help?
This question already has answers here:
Counting longest occurrence of repeated sequence in Python
(5 answers)
Closed 1 year ago.
I am trying to get a length of a Small string that repeats large string continuously in Python
I Tried...
def repeats(string):
for x in range(1, len(string)):
substring = string[:x]
if substring * (len(string)//len(substring))+(substring[:len(string)%len(substring)]) == string:
return "break"
print(len(substring))
But it's long..
Plese Give me your knowledge.
You might be able to use a regex re.findall approach here:
def longest_repeat(x):
matches = re.findall(r'(.+)\1+', x)
matches.sort(key=lambda s: len(s), reverse=True)
if not matches:
return ''
else:
return matches[0]
inp = ["agtcaggtccaggtccgatcgaatac", "agtcgggggggatta", "agtctgcatgac"]
for i in inp:
output = longest_repeat(i)
print(i + ', ' + output)
This prints:
agtcaggtccaggtccgatcgaatac, caggtc
agtcgggggggatta, ggg
agtctgcatgac,
This question already has answers here:
Comparing digits in an integer in Python
(3 answers)
Closed 3 years ago.
How to add numbers that begin with 1 to a list?
def digit1x(lx):
list = []
for num in lx:
temp = str(num)
if temp[0]== '1':
list.append(int(temp))
return list
print(digit1x(lx))
updated code, and It works, thank you for your help!
You're thinking of numbers as starting with 1 in their base 10 representation? In that case, you should coerce to a string first before checking the digit:
>>> num = 12345
>>> str(num)
'12345'
>>> str(num)[0]
'1'
you cannot do num[0] if num is an int, for example you can write str(num)[0] == '1'. Don't forget to deal with special cases if any.
The error is occuring because you cannot get the [0] index value of an integer. It is only posible to get an index value of an array or string. Create a variable ('temp'↓) that is the string variable of the [0] index of that integer and then use that in the conditional statement:
This works:
def digit1x(lx):
list = []
for num in lx:
temp = str(lx[num])
if temp[0] == '1':
list.append(temp)
return list
print(digit1x(lx))
The value of temp is the string value of the current item.
'temp[0]' is the first character in temp, and therefore the first character in the current item.
Therefore, if temp[0] equals '1' then the first number in the current item is 1.
This question already has an answer here:
Run Length Encoding Python
(1 answer)
Closed 4 years ago.
Need to write a python function which performs the run length encoding for a given string and returns the run length encoded String.
Went through various posts in Stack Overflow and other websites in Google to get a proper understanding in Run Length Encoding in Python. Tried coding and got some output but it doesn't match the specified output. I have stated my code and output below:
def encode(input_string):
characters = []
result = ''
for character in input_string:
# End loop if all characters were counted
if set(characters) == set(input_string):
break
if character not in characters:
characters.append(character)
count = input_string.count(character)
result += character
if count > 1:
result += str(count)
return result
#Provide different values for message and test your program
encoded_message=encode("ABBBBCCCCCCCCAB")
print(encoded_message)
For the above string, I am getting the output as : A2B5C8
But the expected output is :1A4B8C1A1B
It would be really great if someone tell me where to make changes in the code to get the expected format of output.
You can use the following function to get the desired output:
string = "ABBBBCCCCCCCCAB"
def encode(string):
counter = 1
result = ""
previousLetter = string[0]
if len(string)==1:
return str(1) + string[0]
for i in range(1,len(string),1):
if not string[i] == previousLetter:
result += str(counter) + string[i-1]
previousLetter = string[i]
counter = 1
else:
counter += 1
if i == len(string)-1:
result += str(counter) + string[i]
return result
result = encode(string)
print(result)
Output:
1A4B8C1A1B
This question already has answers here:
How to merge lists into a list of tuples?
(10 answers)
Closed 7 years ago.
My goal is to write a program which compares two strings and displays the difference between the first two non-matching characters.
example:
str1 = 'dog'
str2 = 'doc'
should return 'gc'
I know that the code which I have tried to use is bad but I am hoping to receive some tips. Here is my poor attempt to solve the exercise which leads me to nowhere:
# firstly I had tried to split the strings into separate letters
str1 = input("Enter first string:").split()
str2 = input("Enter second string:").split()
# then creating a new variable to store the result after comparing the strings
result = ''
# after that trying to compare the strings using a for loop
for letter in str1:
for letter in str2:
if letter(str1) != letter(str2):
result = result + letter
print (result)
def first_difference(str1, str2):
for a, b in zip(str1, str2):
if a != b:
return a+b
Usage:
>>> first_difference('dog','doc')
'gc'
But as #ZdaR pointed out in a comment, result is undefined (in this case None) if one string is a prefix of the other and has different length.
I changed the solution by using a single loop.
How about this:
# First, I removed the split... it is already an array
str1 = input("Enter first string:")
str2 = input("Enter second string:")
#then creating a new variable to store the result after
#comparing the strings. You note that I added result2 because
#if string 2 is longer than string 1 then you have extra characters
#in result 2, if string 1 is longer then the result you want to take
#a look at is result 2
result1 = ''
result2 = ''
#handle the case where one string is longer than the other
maxlen=len(str2) if len(str1)<len(str2) else len(str1)
#loop through the characters
for i in range(maxlen):
#use a slice rather than index in case one string longer than other
letter1=str1[i:i+1]
letter2=str2[i:i+1]
#create string with differences
if letter1 != letter2:
result1+=letter1
result2+=letter2
#print out result
print ("Letters different in string 1:",result1)
print ("Letters different in string 2:",result2)