Python - Removing whitespace on output - python

So, I have this code:
print("%d" % a, end=(" "))
It works, but in the output, there's a whitespace after the last number. I need to get rid of the last whitespace. My output needs to be shown on the same line, separated by a blank space. There should be no space after the last value.
Here's an example: (n is input, so suppose n = 5)
0 1 1 2 3
I've tried .strip, .join, but none of them worked. What do i have to do to get the right output? I'm sorry if this is too much of a simple question, I'm new in python.
edit: edit2:
a, b, i = 0, 1, 0
n=int(input())
for j in range(0, n):
while i < n:
print("%d" % a)
a, b = b, a + b
i += 1

You are adding the trailing space yourself with the end argument.
print("%d" % a, end=(" "))
Means print a ending in a ' '. Remove the end argument and the trailing space will no longer be printed (the default '\n' will be printed instead). See the docs for print() for more details.
Note also, that the end argument does not affect the string you are printing, i.e., a is not affected by end. If there is a trailing space in a string a, then a.strip() will remove that space. The reason it doesn't get removed by strip() in your case is that the space is not in the string you are printing, but instead is added to the visual output by the print() function.
Update:
It is hard to say, because it is a mystery what happens before or after the code snippet in your edit, but it sounds like you want to do something like:
a, b, i = 0, 1, 0
n=int(input())
nums = []
for j in range(0, n):
while i < n:
nums.append(str(a))
...
# Based on your desired output,
# I assume you modify the value of `a` somwhere in here
...
print(' '.join(nums))

Related

How to delete randomly inserted characters at specific locations in a string?

I was previously working on a problem of String encryption: How to add randomly generated characters in specific locations in a string? (obfuscation to be more specific).
Now I am working on its second part that is to remove the randomly added characters and digits from the obfuscated String.
My code works for removing one random character and digit from the string (when encryption_str is set to 1) but for removing two, three .. nth .. number of characters (when encryption_str is set to 2, 3 or n), I don't understand how to modify it.
My Code:
import string, random
def decrypt():
encryption_str = 2 #Doesn't produce correct output when set to any other number except 1
data = "osqlTqlmAe23h"
content = data[::-1]
print("Modified String: ",content)
result = []
result[:0] = content
indices = []
for i in range(0, encryption_str+3): #I don't understand how to change it
indices.append(i)
for i in indices:
del result[i+1]
message = "".join(result)
print("Original String: " ,message)
decrypt()
Output for Encryption level 1 (Correct Output)
Output for Encryption level 2 (Incorrect Output)
That's easy to append chars, that's a bit more difficult to remove them, because that changes the string length and the position of the chars.
But there is an easy way : retrieve the good ones, and for that you just need to iterate with the encryption_str+1 as step (that avoid adding an if on the indice)
def decrypt(content, nb_random_chars):
content = content[::-1]
result = []
for i in range(0, len(content), nb_random_chars + 1):
result.append(content[i])
message = "".join(result)
print("Modified String: ", content)
print("Original String: ", message)
# 3 lines in 1 with :
result = [content[i] for i in range(0, len(content), nb_random_chars + 1)]
Both will give hello
decrypt("osqlTqlmAe23h", 2)
decrypt("osqFlTFqlmFAe2F3h", 3)
Why not try some modulo arithmetic? Maybe with your original string, you try something like:
''.join([x for num, x in enumerate(data) if num % encryption_str == 0])
How about a list comprehension (which is really just a slightly more compact notation for #azro's answer)?
result = content[0::(encryption_str+1)]
That is, take every encryption_str+1'd character from content starting with the first.

Addition binary numbers [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I need a help of my code, i have make addition of passing two variable of two binary numbers and the answer is incorrect!
in my code
import data as s
s.num
s.demo
def add_binary_nums(x,y):
max_len = max(len(x), len(y))
x = x.zfill(max_len)
y = y.zfill(max_len)
result = ''
carry = 0
for i in range(max_len-1, -1, -1):
r = carry
r += 1 if x[i] == '1' else 0
r += 1 if y[i] == '1' else 0
result = ('1' if r % 2 == 1 else '0') + result
carry = 0 if r < 2 else 1
if carry !=0 : result = '1' + result
return result.zfill(max_len)
print("start here")
demoo = (add_binary_nums(s.num,s.demo))
print(demoo)
assume the values as num="011000100110111101100010" and demo="001" and the answer of above code is 011000100110111101100110 , and it's wrong answer! when i pass the value like
num="011000100110111101100010"
demo="001"
i got the the answer 01111011000010110011101010 .
and fpr passing the value like
print(add_binary_nums('001', '001'))
the result will be 01100010011011110110010 i'm getting 3 different results!!
Any suggestion!
space not effect, i remove the space and the answer is same wrong
I tried your script and found out you have an extra space on the right side of your value variable. If you remove it, it should work (returns 010). I would recommend to trim your input values before proceeding with the algorithm.
value = value.strip()
If you just interested in the result but not in implementation (May be you are trying to learn something new or it is an assignment), you can first convert the binary numbers to int and add them and again convert back to binary string.
See this code:
value = '001 '
demo = '001'
def add_binary_nums(x,y):
x_int = int(x, 2)
y_int = int(y, 2)
result = x_int + y_int
return '{0:08b}'.format(result)
print(add_binary_nums(value, demo))
Output:
00000010
To understand '{0:08b}'.format(result), visit this link.
EDIT:
thx, for sure i care about the implementation, its not assignemt or homework to convert numbers into binary, and the code above its peace of my program, im passing many variables have binary number i give u one example , when i pass variable from other python code, assume , n="011000100110111101100010" and m="0001", when i run the code , its shows wrong answer!, remember i'm pass variable and i got result 011000100110111101100110 !
Try the code below. I am getting the right results with python3.
value = '011000100110111101100010'
demo = '0001'
def add_binary_nums(x,y):
x=x.strip()
y=y.strip()
max_len = max(len(x), len(y))
print("Max: %d X: %s Y %s" %(max_len, x, y))
x = x.zfill(max_len)
y = y.zfill(max_len)
result = ''
carry = 0
print("X: %s Y: %s" % (x, y))
for i in range(max_len-1, -1, -1):
print(i)
r = carry
r += 1 if x[i] == '1' else 0
r += 1 if y[i] == '1' else 0
result = ('1' if r % 2 == 1 else '0') + result
carry = 0 if r < 2 else 1
if carry !=0 : result = '1' + result
return result.zfill(max_len)
demoo = (add_binary_nums(demo, value))
print(demoo)
The problem only exists with the trailing space. When running the code with trailing space it produces the output 0011, when running the code without the trailing space produces the output 010
The reason this occurs is due to the space and how you use zfill. If we look at the data when there is a trailing space on one of them.
if we assume x="001" and y='001 ' then max_len will be set as 4 since y has 4 chars in it. you then do zfill on x and zfill on y. this will pad x with an extra leading 0 to make it 4 chars. It will have no effect on y since its already 4 chars. So you will end up with
x="0001"
y="001 "
As you can see these are now not in the same representation. So when you start to do your calculations your first iteration on index 3 will be comparing the "1" from x and the space char from y. You code says if its not a 1 then its a 0. since space isnt a 1 then you default it to a 0.
So your essentially treating it like
x="0001"
y="0010"
and the result of that would indeed correctly be "0011"
So the issue is 100% with your space in the string. I would suggest either validate your input to the function to be sure it contains only 1s or 0s if it doesnt raise a ValueError. Or at a minimum call strip method of string to remove any leading or trailing spaces from the string.
Look at how you initialized your variables (empty space, quotes). Seems off to me for a binary representation...
value = '001 '
demo = "001"
Just use python binary literals: How do you express binary literals in Python?
Rewrite print(add_binary_nums(value, demo)) as print(bin(int(value, 2), int(demo, 2)))
running your code leaves me with the result 0011 not as you mentioned 001001. Leaving out the space in the first "value" variable leaves me with the result 010.
Hope this helps!
Edit: I also would suggest to just add the numbers in int-mode and then convert the int back to binary if you insist in having the space and the input as you have.

Increasing understanding of printing multiple variables [duplicate]

for example in this code below the with the end the integers stay on the same line but without the it does not.
num = 5
for i in range(1, num +1):
for j in range(num, i-1, -1):
print(j, end="")
print()
The end statement for printing in Python allows the programmer to define a custom ending character for each print call other than the default \n
For instance, if you have a function that is to print all values within a list on the same line, you do:
def value(l):
for items in l:
print(l, end=' ')
So if the list argued to this function contains the values [1, 2, 3, 4], it will print them in this manner: 1 2 3 4. If this new ending character parameter was not defined they would be printed:
1
2
3
4
The same principle applies for ANY value you provide for the end option.
In Python 3, the default ist end='\n' for the print function which is a newline after the string is printed.
To suppress this newline, one can set end='' so that the next print starts in the same line.
This is unrelated to the for loop.

Replace all subsequent occurrences of the first character by `$`

The question for the code is 'input a word and check whether the first character of the word is repeated in the word again or not. If yes then change all the repeating characters to $ except the first character.'
So I coded the following and used the logic to start the loop from the second character of the word so that first character remains unchanged.
a=input()
for i in range(1,len(a)):
if(a[i]==a[0]):
b=a.replace(a[i],'$')
print(b)
for the above program I gave the input as 'agra' and to my surprise got the output as '$gr$'. the first character was also changed.
What is the problem with my logic? and what other solution do you suggest?
That is more simply done like:
Code:
b = a[0] + a[1:].replace(a[0], '$')
Test Code:
a = 'stops'
b = a[0] + a[1:].replace(a[0], '$')
print(b)
Results:
stop$
For the correct solution in python, see Stephen Rauch's answer.
I think that what you where trying to achieve, in a very "unpythonic" way, is:
a = input()
b = a # b is a copy
for i in range(1, len(a)):
if a[i] == a[0]:
# replace i-th char of b by '$''
print (b)
How to do that replacement? In python: strings are immutable, that means you cannot replace a char "in place". Try to do this:
a='agra'
a[3] = '$'
And you'll get an error:
TypeError: 'str' object does not support item assignment
If you want to replace the i-th char of a string by $, you have to write:
b = b[:i] + '$' + b[i+1:]
That is: build a new string from b[0], ..., b[i-1], add a $ and continue with b[i+1], ..., b[len(a)-1]. If you use this in your code, you get:
a = input()
b = a
for i in range(1, len(a)):
if a[i] == a[0]:
b = b[:i] + '$' + b[i+1:]
print (b)
Okay, it works but don't do that because it's very "unpythonic" and inefficient.
BEGIN EDIT
By the way, you don't need to replace, you can just build the string character by character:
a = input()
b = a[0] # start with first char
for i in range(1, len(a)):
if a[i] == a[0]:
b += '$' # $ if equals to first char
else:
b += a[i] # else the current char
print (b)
END EDIT
That gave me this idea:
a=input()
b="".join('$' if i!=0 and c==a[0] else c for i,c in enumerate(a))
print(b)
Explanation: the list comprehension takes all characters of a along with their position i (that's what enumerate does). For every couple position, character, if the position is not 0 (not the first character) and if the character is equal to a[0], then put a $. Else put the character itself. Glue everything together to make a new string.
Again, that's not the right way to do what you are trying to do, because there is another way that is neater and easier (see Stephen Rauch's answer), but is shows how you can sometimes handle difficulties in python.
a=input()
for i in range(1,len(a)):
if(a[i]==a[0]):
b=a[1:len(a)].replace(a[i],'$')
print(a[0]+b)
you changed whole word/sentence 'a': a.replace(...)

how to make an imputed string to a list, change it to a palindrome(if it isn't already) and reverse it as a string back

A string is palindrome if it reads the same forward and backward. Given a string that contains only lower case English alphabets, you are required to create a new palindrome string from the given string following the rules gives below:
1. You can reduce (but not increase) any character in a string by one; for example you can reduce the character h to g but not from g to h
2. In order to achieve your goal, if you have to then you can reduce a character of a string repeatedly until it becomes the letter a; but once it becomes a, you cannot reduce it any further.
Each reduction operation is counted as one. So you need to count as well how many reductions you make. Write a Python program that reads a string from a user input (using raw_input statement), creates a palindrome string from the given string with the minimum possible number of operations and then prints the palindrome string created and the number of operations needed to create the new palindrome string.
I tried to convert the string to a list first, then modify the list so that should any string be given, if its not a palindrome, it automatically edits it to a palindrome and then prints the result.after modifying the list, convert it back to a string.
c=raw_input("enter a string ")
x=list(c)
y = ""
i = 0
j = len(x)-1
a = 0
while i < j:
if x[i] < x[j]:
a += ord(x[j]) - ord(x[i])
x[j] = x[i]
print x
else:
a += ord(x[i]) - ord(x[j])
x [i] = x[j]
print x
i = i + 1
j = (len(x)-1)-1
print "The number of operations is ",a print "The palindrome created is",( ''.join(x) )
Am i approaching it the right way or is there something I'm not adding up?
Since only reduction is allowed, it is clear that the number of reductions for each pair will be the difference between them. For example, consider the string 'abcd'.
Here the pairs to check are (a,d) and (b,c).
Now difference between 'a' and 'd' is 3, which is obtained by (ord('d')-ord('a')).
I am using absolute value to avoid checking which alphabet has higher ASCII value.
I hope this approach will help.
s=input()
l=len(s)
count=0
m=0
n=l-1
while m<n:
count+=abs(ord(s[m])-ord(s[n]))
m+=1
n-=1
print(count)
This is a common "homework" or competition question. The basic concept here is that you have to find a way to get to minimum values with as few reduction operations as possible. The trick here is to utilize string manipulation to keep that number low. For this particular problem, there are two very simple things to remember: 1) you have to split the string, and 2) you have to apply a bit of symmetry.
First, split the string in half. The following function should do it.
def split_string_to_halves(string):
half, rem = divmod(len(string), 2)
a, b, c = '', '', ''
a, b = string[:half], string[half:]
if rem > 0:
b, c = string[half + 1:], string[rem + 1]
return (a, b, c)
The above should recreate the string if you do a + c + b. Next is you have to convert a and b to lists and map the ord function on each half. Leave the remainder alone, if any.
def convert_to_ord_list(string):
return map(ord, list(string))
Since you just have to do a one-way operation (only reduction, no need for addition), you can assume that for each pair of elements in the two converted lists, the higher value less the lower value is the number of operations needed. Easier shown than said:
def convert_to_palindrome(string):
halfone, halftwo, rem = split_string_to_halves(string)
if halfone == halftwo[::-1]:
return halfone + halftwo + rem, 0
halftwo = halftwo[::-1]
zipped = zip(convert_to_ord_list(halfone), convert_to_ord_list(halftwo))
counter = sum([max(x) - min(x) for x in zipped])
floors = [min(x) for x in zipped]
res = "".join(map(chr, floors))
res += rem + res[::-1]
return res, counter
Finally, some tests:
target = 'ideal'
print convert_to_palindrome(target) # ('iaeai', 6)
target = 'euler'
print convert_to_palindrome(target) # ('eelee', 29)
target = 'ohmygodthisisinsane'
print convert_to_palindrome(target) # ('ehasgidihmhidigsahe', 84)
I'm not sure if this is optimized nor if I covered all bases. But I think this pretty much covers the general concept of the approach needed. Compared to your code, this is clearer and actually works (yours does not). Good luck and let us know how this works for you.

Categories