How to convert an integer into string without using in-built function? - python

I wanna ask how to convert an integer into string without using in-built function.
This is the original question:
Write a function string(ls) that returns a string representation of the list ls.
Note: do not use the built-in str() method for this task. We are attempting to emulate its behavior.
s = string(['a','b','c']) # '['a','b','c']'
s = string([1,2,3]) # '[1, 2, 3]'
s = string([True]) # '[True]'
s = string([]) # '[]'
Restrictions: Don't just return str(ls)! Don't use the str.join method, don't use slicing.
Here is my code:
def string(ls):
if len(ls)==0:
mess="'[]'"
return mess
elif isinstance(ls[0],str):
i=0
mess="'["
while True:
if i==len(ls)-1:
elem="'"+ls[i]+"'"
mess=mess+elem
break
else:
elem="'"+ls[i]+"', "
mess=mess+elem
i=i+1
mess=mess+"]'"
return mess
else:
i=0
mess="'["
while True:
if i==len(ls)-1:
elem=str(ls[i])+"]'"
mess=mess+elem
break
else:
elem=str(ls[i])+', '
mess=mess+elem
i=i+1
return mess

You can keep dividing a given integer by 10 and prepending the remainder to the output string. Use the ordinal number of '0' plus the remainder to obtain the ordinal number of the remainder, and then convert it to string using the chr function:
def int_to_string(i):
string = ''
while True:
i, remainder = divmod(i, 10)
string = chr(ord('0') + remainder) + string
if i == 0:
break
return string
so that:
print(int_to_string(0))
print(int_to_string(5))
print(int_to_string(65))
print(int_to_string(923))
would output:
0
5
65
923

This should work? I am fairly new so i do not know why your codes are so complicated.This should work too.
def int_to_string(i):
string = chr(ord("0") + i)
return string

Related

Str to int function

I am supposed to write a function that lets the user put in any string of numbers and then turns that input into an int list (e.g "12635 1657 132651627"). However, I don't know how to change this bit of code so that the user can actually put something into the console. When I try to introduce a new variable Python says that there is no value assigned to it, and I do not know how to work around that. I want everything to be within the function. I managed to introduce a new variable before the start of the function but that's not really my aim here.
def Int_Split(a):
List = []
last = 0
max = len(a)
for i in range (max):
if a[i] =="":
nmbr = a[last:i]
last = i+1
List.append(int(nbmr))
nmbr = a[last:]
List.append(int(nmbr))
return List
print(List)
It isn't clear what your issue is with adding a variable, or entirely what you're after. But if you are after converting "12635 1657 132651627" to [12635, 1657, 132651627], that can be done very simply with:
s = "12635 1657 132651627"
l = [int(x) for x in s.split()]
print(l)
Which yields:
[12635, 1657, 132651627]
Here is an example in a function:
def main():
print("input some numbers:")
s = input()
print([int(x) for x in s.split()])
if __name__ == "__main__":
main()
Here we print the request for input, set the value given to s, then use a list comprehension to say: split a string on any whitespace, then give the integer value for each.
Here is a method without using string.split():
def sep(s):
words = []
word = ""
for c in s:
if c != " ":
word += c
continue
words.append(word)
word = ""
else:
words.append(word)
return words
def main():
print("input some numbers:")
s = input()
print([int(x) for x in sep(s)])
if __name__ == "__main__":
main()
Here we have written a function called sep, which just iterates over characters in the given string until it finds a space or the end, each time adding that group of characters to a list of strings.

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 to fix 'TypeError: not all arguments converted during string formatting' in Python [duplicate]

This question already has answers here:
How do I parse a string to a float or int?
(32 answers)
Convert all strings in a list to integers
(11 answers)
Closed 7 months ago.
I'm trying to make a code to get two keys from a master key. The key must be a string. For the first, you have to take the even number and for the second, the odds numbers. E.g.: Master key = 18923. First Key = 82, second Key = 193.
I am new to python.
masterKey = '18293'
firstKey = ''
secondKey = ''
masterKeyList = list(masterKey)
firstKeyList = list(firstKey)
secondKeyList = list(secondKey)
for digit in masterKeyList:
if digit % 2 == 0: # <--- here is the error
firstKeyList.append(digit)
else:
secondKeyList.append(digit)
Error message
TypeError: not all arguments converted during string formatting
I want to know why this happens, and a solution. Thank you!
digit is a string. Just typecast it using int():
if not int(digit) % 2:
The reason your error is occurring is because the modulus operator is also a string formatting operator, but you haven't provided the necessary arguments to string-format '2'
This for-loop will work:
for digit in masterKeyList:
if not int(digit) % 2:
firstKeyList.append(digit)
else:
secondKeyList.append(digit)
This error is occurring because digit is a string, and % in the context of strings is a format operator.
To fix it, convert it into an integer:
...
if int(digit) % 2 == 0:
...
digit is a string in your code, so if you want to apply modulo 2 you need to convert it to a number. That should work fine:
masterKey = '18293'
firstKey = ''
secondKey = ''
masterKeyList = list(masterKey)
firstKeyList = list(firstKey)
secondKeyList = list(secondKey)
for digit in masterKeyList:
if int(digit) % 2 == 0: <--- fixed
firstKeyList.append(digit)
else:
secondKeyList.append(digit)
This can be simplified and shortened using list comprehension and join() if you need strings. In case you prefer lists then just remove the join(). You can do something like the following:
masterKey = '18293'
firstKey = "".join([e for e in masterKey if int(e) % 2 == 0])
secondKey = "".join([e for e in masterKey if int(e) % 2 != 0])

Conversion of string to upper case without inbuilt methods

I am trying to perform conversion from a lowercase to uppercase on a string without using any inbuilt functions (other than ord() and char()). Following the logic presented on a different thread here , I came up with this.
def uppercase(str_data):
ord('str_data')
str_data = str_data -32
chr('str_data')
return str_data
print(uppercase('abcd'))
However I am getting an error output: TypeError: ord() expected a character, but string of length 8 found.What am I missing here?
You need to execute ord() for each character of your input string. instead of the input string:
def uppercase(str_data):
return ''.join([chr(ord(char) - 32) for char in str_data if ord(char) >= 65])
print(uppercase('abcdé--#'))
>>> ABCDÉ
Without join:
def uppercase(str_data):
result = ''
for char in str_data:
if ord(char) >= 65:
result += chr(ord(char) - 32)
return result
print(uppercase('abcdé--#λ'))
>>> ABCDÉΛ
The best way, in my opinion is using a helper string, representing the alphabet, if you do not want to use chr() and ord():
def toUppercase(s):
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
result = ''
for x in s:
if x not in alphabet or alphabet.index(x)>=26:
result += x
else:
result += alphabet[alphabet.index(x)+26]
return result
This also handles punctuation such as ; or ..
Update:
As per the OP's request, this is a version without index():
def toUppercase(s):
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
result = ''
for x in s:
for pos in range(52):
if alphabet[pos] == x:
i = pos
if x not in alphabet or i>=26:
result += x
else:
result += alphabet[i+26]
return result
print(toUppercase('abcdj;shjgh'))
Here is a program to convert the string to uppercase without using inbuilt functions:
Str1=input("Enter the string to be converted uppercase: ")
for i in range (0,len(Str1)):
x=ord(Str1[i])
if x>=97 and x<=122:
x=x-32
y=chr(x)
print(y,end="")
ord()- Return the Unicode code point for a one-character string.
You have to send a one character string as an argument. Here, you are sending the string 'abcd' which has 4 characters which is causing the issue. Send each character separately to the function and thus do 4 calls to the function to get the result.
The below-simplified code help to convert Lower-case alphabets to Upper-case alphabets using a simple calculation
code :
def toUppercase(string):
convertedCharacter = ''
for i in string:
convertCharacter += chr( ( (ord(i)) -32) )
return convertCharacter
char=input("Enter lowercase word :")
for letter in char:
s=ord(letter)
if s>=97 and s<=122:
print(chr(s-32),end=" ")
def uppercase(str_data):
ord('str_data')
str_data = str_data -32
chr('str_data')
return str_data
print(uppercase('abcd'))
in this code ord takes single character as an argument but you have given more than one that's why it's showing an error. Take single character at a time convert it to upper case and make a single string like below.
def convert_to_lower(string):
new=""
for i in string:
j=ord(i)-32 #we are taking the ascii value because the length of lower
#case to uppercase is 32 so we are subtracting 32
if 97<=ord(i)<=122 : #here we are checking whether the charecter is lower
# case or not if lowercase then only we are converting into
#uppercase
new=new+chr(j)
else: #if the character is not the lowercase alplhaber we are taking as it is
new=new+i
print(new)
convert_to_lower("hello world")

Create a funcction which transform a str(binary code) in str(real words)?

Hi i need create a function which I put a binary and the function give me the string. Ican put a lots of words in binary and my function converts this in words reals (ASCII). i cant use list of comprehension and bitewise xor.
Something like that but no that.
Thanks for helping me
def binario_a_string(s):
message = ""
while s != "":
i = chr(int((s[:8]), 2))
message = message + i
s = s[8:]
return (message)
print(binario_a_string("00010000"))
def binario_a_string(s):
if len(s) % 8: raise Exception("Input string's length must be a multiple of 8")
message = ""
for i in xrange(0, len(s), 8):
message += chr(int((s[i:i+8]), 2))
return (message)
print(binario_a_string("010000010100001001000011"))
Output
ABC
You can use range functions to skip 8 indexes at a time.

Categories

Resources