I have a task to create a row of numbers. what I have now works and prints on one line. I want to try to use it without end. What I've tried already is creating a variable new_line = "" and adding that / equaling that to the string in the print line. I also need to be able to print another "|" at the end of the string only and I can't do that with end.
def print_row(n, max_power, column_width):
count = 0
exponent = max_power
max_power = 0
while count < exponent:
max_power = max_power + 1
value = power(n, max_power)
print("|",padded(value, column_width),end='')
count = count + 1
You're using the loop to control the wrong thing. Use the loop to build a list of values to be combined using | as a separator, then print that string with one call to print.
def print_row(n, max_power, column_width):
values = [padded(power(n, p), column_width) for p in range(max_power)]
print("|" + "|".join(values), end="|")
The initial "|" can be added to the value to actually print (as shown), or could be output with a preceding call to print("|", end='').
Related
The task consists to complete the function which takes a string, and returns an array with rotation of the given string, in uppercase. This function moves each first character of the string to the end, and stops once the string returns to its original state as below:
'cat'
'atc'
'tca'
The problem is that my code returns ['atc', 'atc', 'atc']. Where's the problem?
def scrolling_text(text):
returned_text = text.upper()
list_of_switchs = []
text_length = len(text)
while len(list_of_switchs) <= text_length:
switch = returned_text[-1:] + returned_text[:-1]
list_of_switchs.append(switch)
if len(list(list_of_switchs)) == text_length:
break
return list_of_switchs
The problem is in "switch = returned_text[-1:] + returned_text[-1]"
You are reversing the variable "returned_text" 3 times. Since that variable doesn't change at all and only takes in the text and changes it to uppercase, nothing is changing and you will get the same thing printed three times.
To make this work, you would need to change the returned_text variable. Try this:
def scrolling_text(text):
returned_text = text.upper()
list_of_switchs = []
text_length = len(text)
while len(list_of_switchs) <= text_length:
switch = returned_text[-1:] + returned_text[:-1]
list_of_switchs.append(switch)
returned_text = switch
if len(list(list_of_switchs)) == text_length:
break
return list_of_switchs
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 know the title may not be the best, as i'm not exactly how to explain my problem in short words. However i recently was looking at some codes online and i didn't get the reason why some code was used i tried looking on the internet but as i dont know what that part of the code is called ive no idea what to search up so you guys are my last hope.
In this function
def NumIntoChar(LineLis):
for n in LineLis:
string = "" # Here is what im not sure. why is this used here ?
for i in range(n):
string += '-'
print(string)
Im unsure why string = "" is used between the 2 for looks
another example is:
message = """SAHH""" # Add Code
message = message.upper()
keyShift = 1
encryptedMsg = ""
result = {}
while keyShift <= 26:
encryptedMsg = ""
for character in message:
if character.isalpha() is True:
x = ord(character) - 65
x += keyShift
x = x % 26
encryptedMsg += chr(x + 65)
else:
encryptedMsg += character
result[keyShift] = encryptedMsg
keyShift += 1
for r in result.keys():
print(r,result[r])
Here we see ' encryptedMsg = "" ' being used just like in the previous code.
Just below that line of code, you have this for loop:
for i in range(n):
string += '-'
The x += y operator is syntactic sugar for x = x + y. In order to use this operator, x must have a defined value first.
For the first iteration of the loop, string will essentially be assigned like this:
string = string + '-'
In order to avoid NameError being thrown, string first needs to be declared and assigned some value, which is what string = "" does. The expression in the first iteration of the loop then essentially becomes:
string = '' + '-'
Here you initialize a variable with empty string using var = ''.
It is commonly followed in scenarios where you have to iteratively concatenate content to form a bigger string. Your code starts with initializing the empty string and within the loop, content of the string is concatenated. For example:
my_str = ""
while repeat:
my_str += some_str
# Do some stuff
Other scenario in which you might need it is: when you have to set default value of string as empty, but based on some condition reset the content of string. For example:
my_name = ''
if user.is_logged_in():
my_name = user.name
Also read: Initialize a string variable in Python: “” or None?
I've been given a task to split lines into words and then split the lines up based on spaces and newlines. I've came up with an incomplete solution as it will not print the last word. I can only use linear search hence the basic approach.
line = raw_input()
while line != "end":
i = 0
while i < len(line):
i = 0
while i < len(line) and line[i] == " ":
i = i + 1
j = i
while line[j] != " ":
j = j + 1
print line[i:j]
line = line[j:]
line = raw_input()
I understand your problem this is somewhat similar to the Hackerearth problem
See this example to clarify your concept
y=list()
1). y=map(int,raw_input().split()) # for storing integer in list
2). y=map(str,raw_input().split()) # for storing characters of string in list
#then use this to print the value
for i in y:
print i #this loop will print one by one value
#working example of this code is #for Second part
>>baby is cute #input
>>['baby','is','cute'] #output
>> #now according to your problem line is breaks into words
If you find it useful Thumbs up
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