Python: add a newline to a variable - python

I was working on some exercises for school and I can't get over this problem. Is there any way to add a newline to a variable? I tried just concatenating \n but it doesn't work. I want it to be able to return allPrimes with every number on a separate line.
def all_primes_upto(x):
allPrimes = ''
for i in range(x):
if is_prime(i):
allPrimes += i + '\n'
return allPrimes

Don't; your function should return a list of primes; the caller can join them into a single string if they want.
def all_primes_upto(x):
return [i for i in range(x) if is_prime(i)]
prime_str = '\n'.join(str(x) for x in all_primes_upto(700))

If you instead stored the values in a list, you could then print each item out one by one on individual lines
def all_primes_upto(x):
allPrimes = []
for i in range(x):
if is_prime(i):
allPrimes.append(i)
return allPrimes
l = all_primes_upto(10)
for i in l:
print(i)

The problem is that you are trying to use the + operator on variables of different types: i is an int; '\n' is a str. To make the + work as a string concatenation you need both variables to be of type str. You can do that with the str function:
allPrimes += str(i) + '\n'
Note, however, that the other answers suggesting that your all_primes_upto function could return a list that the caller can join and print are better solutions.

Right usage:
def all_primes_upto(x):
allPrimes = ''
for i in range(x):
if is_prime(i):
allPrimes += i + '\n'
print(allPrimes)
use print instead of return

Related

Hacker rank string separated challenge

I'm trying to solve a hacker rank challenge:
Given a string, s , of length n that is indexed from 0 to n-1 , print its even-indexed and odd-indexed characters as 2 space-separated strings. on a single line (see the Sample below for more detail)
link: https://www.hackerrank.com/challenges/30-review-loop/problem
Error:
for example:
The input "adbecf" should output "abc def"
When I run python Visualizer my code seem to have the correct output.. but on hacker rank it's saying I have the wrong answer. Does anyone know what might be wrong with my code.
This is the code I tried -
class OddEven:
def __init__(self, input_statement):
self.user_input = input_statement
def user_list(self):
main_list = list(user_input)
even = []
odd = []
space = [" "]
for i in range(len(main_list)):
if (i%2) == 0:
even.append(main_list[i])
else:
odd.append(main_list[i])
full_string = even + space + odd
return(full_string)
def listToString(self):
my_string = self.user_list()
return(''.join(my_string))
if __name__ == "__main__":
user_input = str(input ())
p = OddEven(user_input)
print(p.listToString())
First of all, input is always string, you don't need to convert it here.
user_input = str(input())
Each line is provided to you as separate input. Number of strings equal to num in the first line. In this case 2, so...
count = input()
for s in range(int(count)):
...
user_input variable inside user_list function should be accessed as self.user_input, it's a property of an object, which you pass to function as self.
Also you can iterate over list directly.
Here:
full_string = even + space + odd
you're trying to concatenate list, which is not a good idea, you'll still get a list.
You can join list with separating them with some string using join string method.
' '.join(list1, list2, ..., listN)
It's better do define odd and even as empty strings.
And then join them the using concatenation (+).
Here:
if (i%2) == 0
you don't have to compare with 0. Python will evaluate what's to the right from condition as True or False. So:
if i % 2:
...
There is simpler solution:
def divide(self):
odd = even = ''
for i, c in enumerate(self.user_input):
if i % 2:
odd += c
else:
even += c
return even + ' ' + odd
Here is the simple code for this problem:)
T=int(input())
for i in range(0,T):
S=input()
print(S[0::2],S[1::2])

How do I remove spaces in a string using a loop in python?

def onlyLetters(s):
for i in range(len(s)):
if s[i] == " ":
s = s[:i] + s[i+1:]
return s
return s
Why is my above loop not working? It seems like it's only doing it once.
For example, if i have the string "Hello how are you", it's returning "Hellohow are you". I want it to check the string again and remove another space, and keep doing it until there are no spaces left. How do I fix this code?
Your code is stopping after the first space is replaced because you've told it to. You have return s inside the loop, and when that is reached, the rest of the loop is abandoned since the function exits. You should remove that line entirely.
There's another issue though, related to how you're indexing. When you iterate on range(len(s)) for your indexes, you're going to go to the length of the original string. If you've removed some spaces, however, those last few indexes will no longer be valid (since the modified string is shorter). Another similar issue will come up if there are two spaces in a row (as in "foo bar"). Your code will only be able to replace the first one. After the first space is removed, the second spaces will move up and be at the same index, but the loop will move on to the next index without seeing it.
You can fix this in two different ways. The easiest fix is to loop over the indexes in reverse order. Removing a space towards the end won't change the indexes of the earlier spaces, and the numerically smallest indexes will always be valid even as the string shrinks.
def onlyLetters(s):
for i in range(len(s)-1, -1, -1): # loop in reverse order
if s[i] == " ":
s = s[:i] + s[i+1:]
return s
The other approach is to abandon the for loop for the indexes and use a while loop while manually updating the index variable:
def onlyLetters(s):
i = 0
while i < len(s):
if s[i] == " ":
s = s[:i] + s[i+1:]
else:
i += 1
return s
If you want to remove all spaces, use str.replace():
sentence = ' Freeman was here'
sentence.replace(" ", "")
>>> 'Freemanwashere'
If you want to remove leading and ending spaces, use str.strip():
sentence = ' Freeman was here'
sentence.strip()
>>> 'Freeman was here'
If you want to remove duplicated spaces, use str.split():
sentence = ' Freeman was here'
" ".join(sentence.split())
>>> 'Freemanwashere'
If you also want to remove all the other strange whitespace characters that exist in unicode you can use re.sub with the re.UNICODE arguement:
text = re.sub(r"\s+", "", text, flags=re.UNICODE)
or something like this,it's handles any whitespace characters that you're not thinking of 😉 :
>>> import re
>>> re.sub(r'\s+', '', 'Freeman was here')
'Freemanwashere'
if you don’t want to use anything like replace() or join() etc. you can do this :
def filter(input):
for i in input:
yield " " if i in " ,.?!;:" else i
def expand(input):
for i in input:
yield None if i == " " else object(), i
def uniq(input):
last = object()
for key, i in input:
if key == last:
continue
yield key, i
def compact(input):
for key, i in input:
yield i
yourText = compact(uniq(expand(filter(input()))))
just use python replace() method for Strings.
s.replace(" ","")
It's a little hard to tell, because the indentation in your example is hard to understand. But it looks to me like after you encounter and remove the very first space, you are returning s. So you only get a chance to remove one space before returning.
Try only returning s once you are out of the for loop.
You can do s.replace(" ", ""). This will take all your spaces (" ") and replace it by nothing (""), effectively removing the spaces.
You're returning the function after the first occurrence of a ",", which means it exits the loop and the function altogether. That's why it's only working for the first comma.
Try this,
def onlyLetters(s):
length=len(s)
i=0
while(i<length):
if s[i] == " ":
s = s[:i] + s[i+1:]
length=len(s)
else
i+=1
return s
If you want to use your own code only then try running this:
def onlyLetters(s):
for i in range(len(s)):
if s[i] == " ":
s = s[:i] + s[i+1:]
return s
or better you may use:
def onlyLetters(s):
return s.replace(" ","")
def remove_spaces(text):
text_with_out_spaces='';
while text!='':
next_character=text[0];
if next_character!=' ':
text_with_out_spaces=text_with_out_spaces +next_character;
text=text[1:];
return text_with_out_spaces
print remove_spaces("Hi Azzam !! ?");

Is there a better way to accomplish this python excercise? (Beginner)

I'm just starting to learn Python and I'm going through an exercise at the end of a chapter. So far, all I've learned about in the book is the very basics, flow control, functions, and lists.
The exercise is:
Comma Code
Say you have a list value like this:
spam = ['apples', 'bananas', 'tofu', 'cats']
Write a function that takes a list value as an argument and returns
a string with all the items separated by a comma and a space, with "and"
inserted before the last item. For example, passing the previous spam list to
the function would return 'apples, bananas, tofu, and cats'. But your function
should be able to work with any list value passed to it.
To solve this, I use the following code (python 3.x.x). I'm wondering if there is a better way to do this. It took a little trial and error, but I fumbled through it until I got this:
myList = ['apples', 'bananas', 'tofu', 'cats']
myList2 = ['apples', 'bananas', 'tofu', 'cats', 'added1', 'added2']
def listFunc(List):
x = 0
for i in List:
x += 1
if x < len(List):
print(i, end=' ')
elif x == len(List):
print('and ' + i)
listFunc(myList2)
Another way to accomplish this would be to use slices and joins:
def listFunc(lst):
if len(lst) == 0: return ''
if len(lst) == 1: return lst[0]
return ", and ".join([", ".join(lst[:-1]), lst[-1]])
Here's a more readable version of the above function using the same core concepts.
def listFunc(lst):
if len(lst) == 0: return '' #no elements? empty string
if len(lst) == 1: return lst[0] #one element? no joining/separating to do, just give it back
firstPart = lst[:-1] #firstPart is now everything except the last element
retFirst = ", ".join(firstPart) #retFirst is now the first elements joined by a comma and a space.
retSecond = ", and " + lst[-1] #retSecond is now ", and [last element]"
return retFirst + retSecond;
The only potentially confusing bits here I think are the slice syntax, negative indices, and string.join
The code lst[:-1] means get everything in lst excepting the last element This is a list slice
The code lst[-1] means get the last element in lst This is negative indexing
And finally, the code ", ".join(firstPart) means get a string containing each element in firstPart separated by a comma and a space
Here is a simple version of the function that doesn't use anything very "fancy" and should be understandable by a beginner. Slicing is probably the most advanced stuff here but should be ok if you went through lists. It also handles two special cases of an empty list and one-item list.
def listFunc(List):
if len(List) == 0: return ''
if len(List) == 1: return List[0]
value = List[0]
for item in List[1:-1]:
value = value + ', ' + item
return value + ', and ' + List[-1]
This is not the way you would normally do it in Python but should be good for learning purposes.
Let's have fun with Python 3 and keep it simple:
def listFunc(myList):
*rest, last = myList
return ", ".join(rest) + (", and " if rest else "") + last
You can make it slightly shorter using enumerate:
def printList():
# x will be the string in the list, y will be an integer
aString = ""
for (y,x) in enumerate(myList):
if y < len(myList) - 1:
aString = aString + x + ", "
else:
aString = aString + "and " + x
.
.
.

How do i reverse a string in python using lists and pop()

I am writing a function to take a string and reverse it. I can't work out why my code is returning a reversed string but with only half of the letters of the string passed to it.
def reverse(text):
temp = []
reverse_text = ""
for i in text:
temp.append(i)
for i in temp:
reverse_text += temp.pop()
print reverse_text
I'm not going to post a complete answer, but:
Don't modify a list you're iterating over with a for loop. Bad things will happen (you already realized that)
You therefore can use a while loop to accomplish the task.
You can also use a for loop, but then you'll end up with for i in range(len(temp)): (see other answers), and the range(len(..)) construct is rather "unpythonic".
def reverse(text)
return text[::-1]
I would just use reversedString = string[::-1], most easy way I think.
Every time you are doing pop operation you are changing the temp over which you are iterating as well.
A simple way would be to just do pop n times where n is the length of temp
def reverse(text):
temp = []
reverse_text = ""
for i in text:
temp.append(i)
print temp
for i in range(len(temp)):
# print i, temp[i]
reverse_text += temp.pop()
print reverse_text
for i in range(len(text)):
reverse_text += temp.pop()
don't change the string.
If you can't do:
text[::-1]
Try doing a for loop:
text = 'Hello'
product=''
for x in range(len(text)-1, -1, -1):
product+=text[x]
return product

What did I do wrong with this function?

I don't know what I did - it's wrong .
Can someone help me?
def insert_sequence(dna1, dna2, number):
'''(str, str, int) -> str
Return the DNA sequence obtained by inserting the second DNA sequence
at the given index. (You can assume that the index is valid.)
>>> insert_sequence('CCGG', 'AT', 2)
'CCATGG'
>>> insert_sequence('TTGC', 'GG', 2)
'TTGGGC'
'''
index = 0
result = '';
for string in dna1:
if index == number:
result = result + dna2
result = result + string
index += 1
print(result)
Here's a solution:
def insert_sequence(dna1, dna2, number):
'''(str, str, int) -> str
Return the DNA sequence obtained by inserting the second DNA sequence
at the given index. (You can assume that the index is valid.)
>>> insert_sequence('CCGG', 'AT', 2)
'CCATGG'
>>> insert_sequence('TTGC', 'GG', 2)
'TTGGGC'
'''
return dna1[:number] + dna2 + dna1[number:]
you needed an if-else loop here :
def insert_sequence(dna1, dna2, number):
result = '';
#you can use enumerate() to keep track of index you're on
for ind,x in enumerate(dna1):
if ind == number: #if index is equal to number then do this
result = result + dna2 +x
else: #otherwise do this
result = result + x
print(result)
insert_sequence('CCGG', 'AT', 2)
insert_sequence('TTGC', 'GG', 2)
output:
CCATGG
TTGGGC
There are already right working functions in other answers (specially the comment from Rakesh Pandit and the answer from JeffS), but your actual question is "why my original function doesn't work".
I copied a working version of your function, comments below:
def insert_sequence(dna1, dna2, number):
index = 0
result = ''
for character in dna1:
if index == number:
result = result + dna2
result = result + character
index += 1
print(result)
Python considers indentation, so you should print only at the end of things, outside loops and ifs.
When you "increase" your result, you do this only inside the "if" on your function, when actually you should increase "for every character in dna1", and only when/"if index == number" you should put the middle string inside.
I believe you are very new to Python or to programming in general, being probably from a biological background, but you really shouldn't iterate to get this type of string operation done, as others have shown.
Hope this helps!
You're never splitting the string apart, so you'll always prepend dna2 to dna1.
You probably want to return dna1[:number] + dna2 + dna1[number:]
You do nothing if the index is not at the insertion point, including incrementing the index. Your code needs an else and you are also printing prematurely:
def insert_sequence(dna1, dna2, number):
index = 0
result = '';
for char in dna1:
if index == number:
result = result + dna2
result = result + char
index += len(dna2) + 1
else:
result = result + char
index += 1
print(result)
mistakes made: a) parameter index is initialised to 0. b) "for sting in dia1:" should have been "for dia1_position in range(len(dia1)):" c) print result indentation is wrong and function isn't just supposed to print. It should return result. d) index need not be incremented now.
Answers are already there. Above briefly lists the mistakes made. I guess you didn't see any error because you never called the function. First error should be "number" not defined (not any more as question has been updated and parameter has number defined).

Categories

Resources