How to strip white spaces in Python without using a string method? - python

I am fairly new to programming and have been learning some of the material through HackerRank. However, there is this one objective or challenge that I am currently stuck on. I've tried several things but still cannot figure out what exactly I am doing wrong.
Objective: Read N and output the numbers between 0 and N without any white spaces or using a string method.
N = int(input())
listofnum = []
for i in range(1, N +1):
listofnum.append(i)
print (*(listofnum))
Output :
1 2 3

N = int(input())
answer = ''
for i in range(1, N + 1):
answer += str(i)
print(answer)
This is the closest I can think of to 'not using any string methods', although technically it is using str.__new__/__init__/__add__ in the background or some equivalent. I certainly think it fits the requirements of the question better than using ''.join.

Without using any string method, just using integer division and list to reverse the digits, print them using sys.stdout.write:
import sys
N = int(input())
for i in range(1,N+1):
l=[]
while(i):
l.append(i%10)
i //= 10
for c in reversed(l):
sys.stdout.write(chr(c+48))
Or as tdelaney suggested, an even more hard-code method:
import os,sys,struct
N = int(input())
for i in range(1,N+1):
l=[]
while(i):
l.append(i%10)
i //= 10
for c in reversed(l):
os.write(sys.stdout.fileno(), struct.pack('b', c+48))
All of this is great fun, but the best way, though, would be with a one-liner with a generator comprehension to do that, using str.join() and str construction:
"".join(str(x) for x in range(1,N+1))
Each number is converted into string, and the join operator just concatenates all the digits with empty separator.

You can print numbers inside the loop. Just use end keyword in print:
print(i, end="")

Try ''.join([str(i) for i in range(N)])

One way to accomplish this is to append the numbers to a blank string.
out = ''
for i in range(N):
out += str(i)
print(out)

You can make use of print()'s sep argument to "bind" each number together from a list comprehension:
>>> print(*[el for el in range(0, int(input())+1)], sep="")
10
012345678910
>>>

You have to do a simple math to do this. What they expect to do is multiply each of your list elements by powers of ten and add them up on each other. As an example let's say you have an array;
a = [2,3,5]
and you need to output;
235
Then you multiply each of loop elements starting from right to left by 10^0, 10^1 and 10^2. You this code after you make the string list.
a = map(int,a)
for i in range(len(a)):
sum += (10**i)*a[-i]
print sum
You are done!

Related

Why doesn't my if...in statement work in python?

this program takes 3 lists of numbers, and compares A and B to the list n. if a term from A is in n, the happiness increases. if a term from B is in n, the happiness decreases. However, when I am doing these calculations, the if ... in statement to check if a term from A/B is in n doesn't work - I have done print(happy) after each one to check, and I get no result
A = []
B = []
n = []
happy = 0
lengthn, lengthAB = input("").split()
for i in lengthn:
numbers = input("")
newNumbers = numbers.split()
n.append(newNumbers)
for i in lengthAB:
numbers = input("")
ANumbers = numbers.split()
A.append(ANumbers)
for i in lengthAB:
numbers = input("")
BNumbers = numbers.split()
B.append(BNumbers)
long = int(lengthAB)
for i in range(long):
j = int(i)
if A[j - 1] in n:
happy = happy + 1
print(happy)
if B[j - 1] in n:
happy = happy - 1
print(happy)
i = i + 1
print(happy)
Thank you so much for the help!!
You appended a list to n, not each element of that list. You can write
n.extend(newNumbers)
instead.
You could just write n = newNumbers.split(), but as pointed out in a comment, you probably have an indentation error:
for i in lengthn:
numbers = input("")
newNumbers = numbers.split()
n.extend(newNumbers)
Or, you don't need split at all:
for i in lengthn:
number = int(input(""))
n.append(number)
At some point, you probably mean to convert the string inputs to integers; may as well do that immediately after reading the string. (I'm declaring various techniques for handling conversion errors beyond the scope of this answer.)
Contrary to what you seem to expect the variables: lengthn, lengthAB are strings
The for-loop
for i in lengthn:
numbers = input("")
iterates over the characters in the string lengthn. If lengthn='12' it will ask to provide input twice.
If lengthAB is '13' for example you will get 2 numbers in your list BNumbers but later on you try to test 13 values because int('13') is 13.
for i in lengthn:
numbers = input("")
so the numbers you are getting are the form of string it's will iterate on string rather then a number.
You should look for beeter python book. Based on desription I think this should look like this:
def happiness(A, B, n):
return sum(x in n for x in A) - sum(x in n for x in B)
def get_data(prompt=""):
return [int(x) for x in input(prompt).split()]
print(happiness(get_data(), get_data(), get_data()))
https://ideone.com/Q2MZCo

Convert x digit number into two digit number

I am currently having x number in a list, and I am trying to convert inconsistent data that may be in 1 digit, 5 digit or 2 digit.
How can I convert all into 2 digit number?
Example:
def List_Convert_2_Digit(z):
for i in range(len(z)):
while(z[i]<100 or z[i]>10):
if(z[i]<100):
z[i]=z[i]/10
else:
z[i]=z[i]*10
return z
list_a = [5.2,1600,520,3600,13,55,4000]
result_list= List_Convert_2_Digit(list_a)
Result should yields: [52,16,52,36,13,55,40]
But the above code does not work and it's running forever.
I've tried mod, but it is not what I am looking for.
It looks like you just want to take the first two characters from each, and if there is a separator (dot in your case) ignore it.
In that case you can do this:
two_digit_list = [int(str(x).replace('.', '')[:2]) for x in List]
If other non numeric characters than a dot are going to appear your would have to deal with those as well of course :)
What this does is just converts the numbers to a string, removes dots and then grabs the first two characters and converts it back to an int.
EDIT: Since I saw you replied to someone above that single digit numbers should have 0 added to the end you can do this instead to cover that case:
two_digit_list = [int(str(x).replace('.', '')[:2]) if len(str(x).replace('.', '')) > 1 else int(f"{x}0") for x in List]
At that point it's a bit too long to be a pretty list comprehension so you could always just break it up into a for loop if it's unclear, might be a good exercise if nothing else :)
This is a simple solve to this.
yield_list = []
number_list = [5.2,1600,520,3600,13,55,4000]
for number in number_list:
string = str(number)
string =string.replace('.', '')
yield_list.append(string[:2])
yield_list
There is an error in your logic; your < and > are flipped. This code works:
def List_Convert_2_Digit(z):
for i in range(len(z)):
while(z[i]>100 or z[i]<10):
if(z[i]>100):
z[i]=z[i]/10
else:
z[i]=z[i]*10
return z
Solution that increases/decreases the numbers magnitude until we can get the left two digits:
def two_digit_list(lst):
rv = []
for item in lst:
if item < 10:
item *= 10
while item > 99:
item //= 10
rv.append(int(item))
return rv

Removing duplicates and sorting list python

Given a list, I need to print the numbers in sorted order and remove any duplicates. I am using python 3.7.2
My code:
def sorted_elements(numbers):
return sorted(set(numbers))
testcase = int(input())
while testcase > 0:
numbers = input().split()
l = sorted_elements(numbers)
for x in l:
print (x, end = ' ')
print ()
testcase -= 1
However, whenever my input consists of a 2 digit number, the logic fails.
Eg. for input of 2 1 43 2 5, I get an output of 1 2 43 5.
This work perfectly for single digit numbers. Can someone help me out with this?
You only need a slight modification. You are comparing strings instead of numbers, so try this instead:
def sorted_elements(numbers):
return sorted(set(numbers))
testcase = int(input())
while testcase > 0:
numbers = map(int, input().split())
l = sorted_elements(numbers)
for x in l:
print (x, end = ' ')
print ()
testcase -= 1
If you want, you can also do:
numbers = (int(x) for x in input().split())
You can simplify this in various aspects. Sort by numeric value using an appropriate key function, use a for loop if you know the number of iterations beforehand, utilize appropriate string utils like str.join, etc.
testcases = int(input())
for _ in range(testcases):
print(' '.join(sorted(set(input().split()), key=int)))
You are going correct way with set(numbers) to remove duplicates. The problem comes from sorted with your numbers being list of strs not ints.
Try this:
x_numbers = input().split()
numbers = [int(x) for x in x_numbers]
Try it now:
testcase = int(input())
n=list(str(testcase))
results = map(int, n)
numbers= sorted(set(results))
print(numbers)
code here:https://repl.it/repls/SeriousRosybrownApplicationprogrammer
We can keep it simple like this. This is a reference
input=raw_input() #took input as string
inputlist=input.split() #split the string to list
lsintegers = map(int, list(set(inputlist))) #remove duplicates converted each element to integer
lsintegers.sort() #sorted
print(lsintegers)`

How to loop to generate string in sequence?

I am trying to create a loop where I can generate string using loop. What I am trying to achieve is that I want to create a small collection of strings starting from 1 character to up to 5 characters.
So, starting from sting 1, I want to go to 55555 but this is number so it seems easy if I just add them, but when it comes to alpha numeric, it gets tricky.
Here is explanation,
I have collection of alpha-numeric chars as string s = "123ABC" and what I want to do is that I want to create all possible 1 character string out of it, so I will have 1,2,3,A,B,C and after that I want to add one more digit in length of string so I can get 11, 12, 13 and so on until I get all possible combination out of it up to CA, CB, CC and I want to get it up to CCCCCC. I am confused in loop because I can get it to generate a temp sting but looping inside to rotate characters is tricky,
this is what I have done so far,
i = 0
strr = "123ABC"
while i < len(strr):
t = strr[0] * (i+1)
for q in range(0, len(t)):
# Here I need help to rotate more
pass
i += 1
Can anyone explain me or point me to resource where I can find solution for it?
You may want to use itertools.permutations function:
import itertools
chars = '123ABC'
for i in xrange(1, len(chars)+1):
print list(itertools.permutations(chars, i))
EDIT:
To get a list of strings, try this:
import itertools
chars = '123ABC'
strings = []
for i in xrange(1, len(chars)+1):
strings.extend(''.join(x) for x in itertools.permutations(chars, i))
This is a nested loop. Different depths of recursion produce all possible combinations.
strr = "123ABC"
def prod(items, level):
if level == 0:
yield []
else:
for first in items:
for rest in prod(items, level-1):
yield [first] + rest
for ln in range(1, len(strr)+1):
print("length:", ln)
for s in prod(strr, ln):
print(''.join(s))
It is also called cartesian product and there is a corresponding function in itertools.

Iterate for loops

alpha = [0,1,2,3,4,5,6,7,8,9]
for a in alpha:
for b in alpha:
for c in alpha:
for d in alpha:
print str(a) + str(b) + str(c) + str(d)
The code above will generate all numbers between 0000 to 9999. However, I do not like the way the code is structured. Let's say I would want to do this to produce numbers up to a ten digit size; that would require 10 for loops. Is there another way the same result could be achieved, without having to insert countless of for loops?
The obvious way:
for i in xrange(10000): # or range if python 3
print "{0:04d}".format(i)
You can also specify the with as an argument:
for i in xrange(10000): # or range if python 3
print "%0*d"%(4,i)
I'm not sure whether you want combinations_with_replacement or product. I think it's the latter, but… try them both with, say, 2 or 3, and see which one is what you're asking for.
for combination in itertools.combinations_with_replacement(alpha, 3):
print ''.join(map(str, combination))
for element in itertools.product(alpha, repeat=3):
print ''.join(map(str, element))
Although I'd probably generate the combinations out of strings, instead of generating them out of integers just to convert them to strings:
alpha = '0123456789'
for combination in itertools.combinations_with_replacement(alpha, 4):
print ''.join(combination)
expect_len = 10
max_val = 10**expected_len -1
my_list = ["%0*d"%(expect_len,val) for val in xrange(0,max_val+1)]
I think at least

Categories