i made var with input word , then the output of word is encode hex , but what i need is to made another var with number if the input are 10 , the output = 1,2,3,4,5,6,7,8,9,10 , then i need to join the word with each number .. so the output would be , hexedWord1,hexedWord2,hexedWord3 ... etc .. here is my code
num = raw_input("Inset the number of students. ")
for num in range(1, num + 1)
print num
word = raw_input("Insert the name of student to encrypt it to hex. ")
res = "0x" + word.encode('hex') + num
print res
It's a little hard to tell what you are asking, but from what I understand, you the encrypted student names separated by commas with their number following the name
There are a few errors with your code. For one, raw_input("Inset the number of students. ") returns a string, but you use it like an integer. To fix this, do num = int(raw_input("Inset the number of students. ")) There are further things you can do to keep the user from giving you something weird, but this will work.
Another problem is with res. For each student, res is being reset. You want the information to be added to it. This could easily be done with a += operator, but if you want them separated by commas, the best thing I can think of is using an array that can be joined together with commas later on.
All together, the code would look like this:
num = int(raw_input("Inset the number of students. "))
res = []
for num in range(1, num + 1):
print num
word = raw_input("Insert the name of student to encrypt it to hex. ")
res.append("0x" + word.encode('hex') + str(num))
print ",".join(res)
Personally, using num as both the iterator of the for loop as well as num feels weird, but I'll let you keep that.
First of all,
when you read input from user using raw_input the value is stored in "num" as string,
So range(1,num+1) throws an error.
So either use
num = input("Inset the number of students. ")
or
num = int(raw_input("Inset the number of students. "))
Secondly,
There is a missing colon(:) at the end of for
fix it like this:
for num in range(1, num + 1):
Thirdly, you are using the same variable "res" for storing the result of every stage, so it gets overwritten.
I prefer you use a list to store values
Declare a empty list before the for loop and append new result to it within the loop
Finally, this statement throws an error
res = "0x" + word.encode('hex') + num
Fix it by:
res = "0x" + word.encode('hex') + str(num)
What happened was that, you tried to concatenate 3 objects of different type using "+" which produces TypeError in Python
the Final code would be something like this:
num = input("Inset the number of students. ")
res = []
for num in range(1, num + 1):
print num
word = raw_input("Insert the name of student to encrypt it to hex. ")
res.append("0x" + word.encode('hex') + str(num))
for r in res:
print r
This should work (Assuming this is what you expect)
Related
I am new to python and I was trying to write a program that gives the frequency of each letters in a string from a specific point. Now my code is giving correct output for some inputs like if I give the input "hheelloo", I get the correct output, but if the input is "hheelllloooo", the frequency of h,e and l is printed correct, but the frequency of 'o' comes out as 7 if the starting point is index 0. Can somebody tell me what am i doing wrong.
Write a Python program that counts the occurrence of Character in a String (Do
not use built in count function.
Modify the above program so that it starts counting
from Specified Location.
str = list(map(str, input("Enter the string : ")))
count = 1
c = int(input("Enter the location from which the count needs to start : "))
for i in range(c, len(str)):
for j in range(i+1,len(str)):
if str[i] == str[j]:
count += 1
str[j] = 0
if str[i] != 0:
print(str[i], " appears ", count, " times")
count = 1
str = list(map(str, input("Enter the string : ")))
count = 1
c = int(input("Enter the location from which the count needs to start : "))
for i in range(c, len(str)):
for j in range(i+1,len(str)):
if str[i] == str[j]:
count += 1
str[j] = 0
if str[i] != 0:
print(str[i], " appears ", count, " times")
count = 1 // <----- This line should be outside the if block.
The error was because of indentation.
I have just properly indented the last line.
Thanks, if it works, kindly upvote.
string module can be useful and easy to calculate the frequency of letters, numbers and special characters in a string.
import string
a='aahdhdhhhh2236665111...//// '
for i in string.printable:
z=0
for j in a:
if i==j:
z+=1
if z!=0:
print(f'{i} occurs in the string a {z} times')
If you want to calculate the frequency of characters from a particular index value, you just have to modify the above code a little as follows:
import string
a='aahdhdhhhh2236665111...//// '
c = int(input("Enter the location from which the count needs to start : "))
for i in string.printable:
z=0
for j in a[c:]:
if i==j:
z+=1
if z!=0:
print(f'{i} occurs in the string a {z} times')
I don't think you need to map the input to list of str as input() always returns a string and string itself is a list of characters. Also make sure you don't use the built-ins as your variable names (As str used in your code). One of the simpler approach can be:
input_word = input("Enter the string : ")
c = int(input("Enter the location from which the count needs to start : "))
# Dict to maintain the count of letters
counts = {}
for i in range(c, len(input_word)):
# Increment 1 to the letter count
counts[input_word[i]] = counts.get(input_word[i], 0)+1
for letter, freq in counts.items():
print (f'{letter} appears {freq} times')
Output:
Enter the string : hheelllloooo
Enter the location from which the count needs to start : 2
e appears 2 times
l appears 4 times
o appears 4 times
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])
I try to extract numbers from a text file with regex. Afterward, I create the sum.
Here is the code:
import re
def main():
sum = 0
numbers = []
name = input("Enter file:")
if len(name) < 1 : name = "sample.txt"
handle = open(name)
for line in handle:
storage = line.split(" ")
for number in storage:
check = re.findall('([0-9]+)',number)
if check:
numbers.append(check)
print(numbers)
print(len(numbers))
for number in numbers:
x = ''.join(number)
num = int(x)
sum = sum + num
print(sum)
if __name__ == "__main__":
main()
The problem is, if this string "http://www.py4e.com/code3/"
I gets add as [4,3] into the list and later summed up as 43.
Any idea how I can fix that?
I think you just change numbers.append(check) into numbers.extend(check)because you want to add elements to an array. You have to use extend() function.
More, you do not need to use ( ) in your regex.
I also tried to check code on python.
import re
sum = 0;
strings = [
'http://www.py4e.com/code3/',
'http://www.py1e.com/code2/'
];
numbers = [];
for string in strings:
check = re.findall('[0-9]+', string);
if check:
numbers.extend(check)
for number in numbers:
x = ''.join(number)
num = int(x)
sum = sum + num
print(sum)
I am assuming instead of 43 you want to get 7
The number variable is an array of characters. So when you use join it becomes a string.
So instead of doing this you can either use a loop in to iterate through this array and covert elements of this array into int and then add to the sum.
Or
you can do this
import np
number np.array(number).astype('int').tolist()
This makes array of character into array on integers if conversion if possible for all the elements is possible.
When I add the string http://www.py4e.com/code3/" instead of calling a file which is not handled correctly in your code above fyi. The logic regex is running through two FOR loops and placing each value and it's own list[[4],[3]]. The output works when it is stepped through I think you issue is with methods of importing a file in the first statement. I replaced the file with the a string you asked about"http://www.py4e.com/code3/" you can find a running code here.
pyregx linkhttps://repl.it/join/cxercdju-shaunpritchard
I ran this method below calling a string with the number list and it worked fine?
#### Final conditional loop
``` for number in numbers:
x = ''.join(number)
num = int(x)
sum = sum + num
print(str(sum)) ```
You could also try using range or map:
for i in range(0, len(numbers)):
sum = sum + numbers
print(str(sum))
I am new to this platform so excuse any mistakes in this question. I am trying to write a program that allows a teacher to input 30 students names and their marks to 3 tests each out of 20, 25 and 35, respectfully. I need it to save the inputted details afterwards, this is where I am having problems. it is not saving the details.
Below is my 'WriteToFile' function:
def WriteFile(Names, MarkTest1, MarkTest2, MarkTest3):
FileName = raw_input('Please Enter The File Name: ')
print
WriteFile = open(FileName, 'w')
Lines = ''
for Pupil in range(len(Names)):
Lines = Lines + str(Names[Pupil]) + ', ' + str(MarkTest1[Pupil]) + ', ' + str(MarkTest2[Pupil]) + ', ' + str(MarkTest3[Pupil]) + '\n'
WriteFile.write(Lines)
WriteFile.close()
Below is part of the program that inputs and saves the details:
if Choice in 'Ww':
for P in range(Pupils):
Name = getName("Please Enter The Students Name: ")
print
Mark1 = getMark("Please Enter The Students Mark For Test 1: ", 20)
print
Mark2 = getMark("Please Enter The Students Mark For Test 2: ", 25)
print
Mark3 = getMark("Please Enter The Students Mark For Test 3: ", 35)
print
Names.append(Name)
MarkTest1.append(Mark1)
MarkTest2.append(Mark2)
MarkTest3.append(Mark3)
WriteFile(Names, MarkTest1, MarkTest2, MarkTest3)
getContinueChoice()
Hope someone can help, Thanks.
IndexError: string index out of range occurs when you try to access a character of string beyond its length among many other reasons.
ex.
a = 'Hello, World!'
print a[0]
print a[42] # This will cause IndexError
b='24'
print b[1] # prints 2
print b[2] # IndexError
In your case, You are trying to access MarkTest1[Pupil].
I see MarkTest1 is Mark1 from the calling function. Which is basically user input.
I am assuming length of Names is greater than this string input. Lets say length of Names is 3. Mark1 is '24' (see this is a string).
In the loop
for Pupil in range(len(Names)):
...
Pupil assumes [0,1,2]
And, when you access MarkTest1[2] which is basically '24'[2] or b[2] in my example.
So, you are getting IndexError.
Now What do you do:
From here you need to debug. See what exactly is each variable before the the error occurs by printing them. Gives you an insight. And, lot of learning.
Have fun debugging :)
The code I'm working on takes an input, and is meant to return a "staircase" of hashes and spaces. For instance, if the input was 5, the result should be:
#
##
###
####
#####
I've turned the input into a list of spaces and hashes, and then converted that to a string form, in order to insert \n in every space corresponding to the length of the input (e.g. every 5 characters above). However, my code prints the result in one line. Where am I going wrong??
x = input()
list = []
a = x-1
while a > -1:
for i in range(0, a):
list.append(" ")
for i in range(0, (x-a)):
list.append("#")
a = a - 1
continue
z = str("".join(list))
t = 0
while t<x:
z = z[t:] + "\n" + z[:t]
t = t + x
continue
print str(z)
Start with pseudocode, carefully laying out in clear English what you want the program to do.
Get a number from the user.
Go through each number from 1 until the user's number, inclusive.
On each line, print a certain number of spaces, starting from one fewer than the user's number and going down to zero, inclusive.
On each line, also print a certain number of hash symbols, starting from one and going up to the user's number, inclusive.
Now you can turn that into Python.
First, get a number from the user. It looks like you're using Python 2, so you could use input() or try the safer raw_input() and cast that to int().
num = input()
Going through each number from one until the user's number, inclusive, means a for loop over a range. On Python 2, using xrange() is better practice.
for i in xrange(1, num+1):
This next part will combine steps 3 and 4, using string multiplication and concatenation. For the spaces, we need a number equal to the max number of lines minus the current line number. For the hash symbols, we just need the current line number. You can multiply a string to repeat it, such as 'hi' * 2 for 'hihi'. Finally, the newline is taken care of automatically as the default end character in a Python 2 print statement.
print ' ' * (num-i) + '#' * i
Put it all together and it looks like this:
num = input()
for i in xrange(1, num+1):
print ' ' * (num-i) + '#' * i
As you discovered, achieving the same effect with an intricate structure of counters, nested loops, list operations, and slicing is more difficult to debug. The problems don't stop when you get it working properly, either - such code is difficult to maintain as well, which is a pain if you ever want to modify the program. Take a look at the official Python tutorial for some great examples of clear, concise Python code.
Try this
x = input()
list1 = []
a = x-1
while a > -1:
for i in range(0, a):
list1.append(" ")
for i in range(0, (x-a)):
list1.append("#")
a = a - 1
list1.append("\n")
continue
z = str("".join(list1))
print z