How to print numbers in steps using function python - python

Am trying to write a function to print numbers in steps.Here is my code
def steps(num):
v = num
for i in range(1, v+1):
print(" "*i + str(i)*3)
print(steps(3))
The result appears as
111
222
333
None
I am trying to get rid of the "none" word any help? Note please, i don't want to get rid of the print statement in "print(steps(3)), any other method or solution will be welcomed.

You need to output the spaces yourself like so:
for i in range(1, v + 1):
print(" " * i + str(i) * 3)

def steps(number):
mystr = ""
for i in range(1, number + 1):
mystr += 3*str(i) + '\n' + i*'\t'
return mystr

Related

How Can I avoid the Trailing whitespace and produce the desired 8 x 8 grid in the code below using Python?, my code is below as well

for i in range(n):
for j in range(n):
z = i * n + j
if z < 10:
print(f" {z}", end = " ")
else:
print(f"{z}" , end = " ")
print()
I have tried the end= " " method but I keep getting the whitespace error, I am a beginner thus I am unable to implement other methods to address the same. The image embedded below has the desired output
[The output required ][1]
[1]: https://i.stack.imgur.com/StAVT.png
This approach creates the full matrix as a string s first and then only prints once in the end:
s = ''
for i in range(n):
for j in range(n):
z = i * n + j
s += ' '
if z < 10:
s += ' '
s += str(z)
s += '\n'
print(s)

Swapping the positions of adjacent characters in a string using indexing and loops in Python

Using just indexing and loops, how do you swap the positions of adjacent characters in a string, while making an exception for spaces?
I/P: HELLO WORLD
O/P: EHLLO OWLRD
This is the code I wrote:
s1=''
for j in range(0,len(s)-1,2):
if(skip==1):
print()
skip=0
elif(s[j].isspace()==False and s[j+1].isspace()==False):
s1=s1+s[j+1]+s[j]
elif(s[j].isspace()==False and s[j+1].isspace()==True):
s1=s1+s[j]+" "
elif(s[j].isspace()==True and s[j+1].isspace()==False and s[j+2].isspace()==False):
s1=s1+" "+s[j+2]+s[j+1]
skip=1
elif(s[j].isspace()==True and s[j+1].isspace()==False and s[j+2].isspace()==True):
s1=s1+" "+s[j+1]
print("new string is",s1)
What exactly am I doing wrong here?
inp = "HELLO WORLD"
expected = "EHLLO OWLRD"
for i in range(0, len(inp), 2): # iterate in steps of two
# check to make sure that we are not at end of string and charaters are not spaces
if i+1 < len(inp) and inp[i] != " " and inp[i+1] != " ":
# now do the string replacing
temp1 = inp[i]
temp2 = inp[i + 1]
inp = inp[:i] + temp2 + temp1 + inp[i+2:]
# output to indicate the new string is what we expect
print(inp)
print(expected)
print(inp == expected)
Another solution:
s = "HELLO WORLD"
out = []
for w in map(list, s.split(" ")):
for i in range(1, len(w), 2):
w[i], w[i - 1] = w[i - 1], w[i]
out.append("".join(w))
print(" ".join(out))
Prints:
EHLLO OWLRD

how to print star hypen pattern in python

How to print the pattern like this:
(need to print n-1 lines)
input=3
----#
--#-#-#
input=6
----------#
--------#-#-#
------#---#---#
----#-----#-----#
--#-------#-------#
My code:
row = int(input())
for i in range(1, row):
for j in range(1,row-i+1):
print("-", end="")
for j in range(1, 2*i):
if j==1 or j==2*i-1:
print("#", end="")
else:
print("-", end="")
print()
MY OUTPUT:
input=5
----#
---#-#
--#---#
-#-----#
Please explain how to do??
There are a few things missing and to be improved in your code:
There's no need to make a loop to print the same character again and again: on python you can use the product to repeat the character an x number of times. For example: "-" * 3 == "---"
They way you calculate the hyphens in the middle is fine, but you need to do it twice and add an "#" in between.
You can build the strings part by part first and then print the whole line, avoiding having to print an empty line in the end of the loop.
Personally, since the first line is going to have one "#" and not three, I prefer to calculate it and print it separately.
With these improvements, a solution to your problem could be:
row = int(input())
print("-" * (row - 1) * 2 + "#")
for i in range(row - 2, 0, -1):
left_hyphens = "-" * i * 2
mid_hyphens = "-" * (1 + 2 * (row - 2 - i))
print(left_hyphens + "#" + mid_hyphens + "#" + mid_hyphens + "#")
row = int(input())
for i in range(1, row):
for j in range(1,2*(row-i)+1):
print("-", end="")
for j in range(1, 4*i):
if j==1 or j==2*i-1 or j==4*i-3:
print("#", end="")
elif j<=4*i-3:
print("-", end="")
print()

Sum of Digits in a specific way in Python

I'm looking for a code that runs, i.e:
int(input) = 2565
Printed Output should be like:
2 + 5 + 6 + 5 = 18 = 1 + 8 = 9
I wrote the code that gives final answer "9". But I couldn't managed to write it with every digit separated "+" sign. Assuming that I need to use while loop but how can I write the code so it will be like the output above?
You can use something like this:
def sum_of_digits(s):
if s < 10:
return s
return sum_of_digits(sum(int(c) for c in str(s)))
> sum_of_digits(2565)
9
It recursively checks if the numerical value is less than 10. If it does, it returns this value. If not, it adds the digits, then recursively calls itself on the result.
Edit
To print out the steps as it goes along, you could do something like this:
def sum_of_digits(s):
if s < 10:
print(s)
return s
print(' + '.join(c for c in str(s)) + ' = ')
return sum_of_digits(sum(int(c) for c in str(s)))
First, initiate an empty string output_str.
With a while loop which contniues when our integer is > 9:
[s for s in str(x)] would create a list of the digits (as strings) of our integer. It's called a list comprehension, is very useful, and my advice is to read a bit about it.
With " + ".join() we create a string with " + " between the
digits. Add this string at the end of output_str.
Add " = " to the end of output_str.
Calculate the sum of the digits (we cannot use sum(lst_of_digits) because it's a list of strings. sum([int(s) for s in lst_of_digits]) converts the string list into an inter list, which can be summed using sum()). Store the sum into x.
Add the new x + " = " to output_string.
At the end of the string, we have a redundant " = " (because the last (5) was not needed), let's just remove the last 3 chars (=) from it.
x = 2565
output_str = ""
while x > 9:
lst_of_digits = [s for s in str(x)]
output_str += " + ".join(lst_of_digits)
output_str += " = "
x = sum([int(s) for s in lst_of_digits])
output_str += f"{x} = "
output_str = output_str[:-3]
outputs:
output_str = '2 + 5 + 6 + 5 = 18 = 1 + 8 = 9'
You can play around with the end keyword argument of the print function which is the last character/string that print will put after all of its arguments are, well, printed, by default is "\n" but it can be change to your desire.
And the .join method from string which put the given string between the given list/iterable of strings to get the desire result:
>>> " + ".join("123")
'1 + 2 + 3'
>>>
Mixing it all together:
def sum_digit(n):
s = sum(map(int,str(n)))
print(" + ".join(str(n)),"=",s, end="")
if s<10:
print()
return s
else:
print(" = ",end="")
return sum_digit(s)
Here we first get the sum of the digit on s, and print it as desire, with end="" print will not go to the next line which is necessary for the recursive step, then we check if done, and in that case print a new empty line if not we print an additional = to tie it for the next recursive step
>>> sum_digit(2565)
2 + 5 + 6 + 5 = 18 = 1 + 8 = 9
9
>>>
This can be easily be modify to just return the accumulated string by adding an extra argument or to be iterative but I leave those as exercise for the reader :)
I am a noob but this should do what you want.
Cheers,
Guglielmo
import math
import sys
def sumdigits(number):
digits = []
for i in range( int(math.log10(number)) + 1):
digits.append(int(number%10))
number = number/10
digits.reverse()
string = ''
thesum = 0
for i,x in enumerate(digits):
string += str(x)
thesum += x
if i != len(digits)-1: string += ' + '
else: string += ' = '
if thesum > 10:
return string,thesum,int(math.log10(number))+1
else:
return string,thesum,0
def main():
number = float(sys.argv[1])
finalstring = ''
string,thesum,order = sumdigits(number)
finalstring += string
finalstring += str(thesum)
while order > 0:
finalstring += ' = '
string,thesum,order = sumdigits(thesum)
finalstring += string
finalstring += str(thesum)
print 'myinput = ',int(number)
print 'Output = ',finalstring
if __name__ == "__main__":
main()

Why count doesn't behave normal in python for loop

I have a text file I'm reading from and just threw a counter on there to make sure I grabbed everything but when I implemented a simple counter it acted weird. It works now but I had to do the following:
f = open("street.txt", "r")
l = ""
count = -1
for line in f:
if(line[0].isdigit()):
l = line.replace('\n', '')
else:
count=count+1
l = l + " " + line.replace('\n', '')
c = str(count) + ')'
print(c + l + '\n')
Essentially I was attempting to just run through this file, add every other line to the previous line then number them just as a check with a count variable, that I covered everything. For some reason when the count was running it started at 2 when I had count initially set to 0. It wouldn't print out "1)" until I changed count to -1 initially. That print statement is an L, not a 1. I have no idea why it was doing that. I didn't get an error, it ran fine just with the wrong numbers for about 4-5 runs. And that's an L in the print statement...which should be fairly obvious from the if statement but just in case.
Just initialize count with 0 and increment statement should be in the last.
l = l + " " + line.replace('\n', '')
c = str(count) + ')'
print(c + l + '\n')
count+=1

Categories