How to turn 1000 into 1e3? [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I want to convert a given number with 0's to be converted to the format with 'e' ex : 1000000 >> 1e6 so far i use this
def test(number: int):
number, zeros = str(number), 0
for i in number:
if i == '0': zeros += 1
return number[0] + 'e' + str(zeros)

You can do that by iterating over stringified number. Code below iterates from end to start of the stringified number and counts the number of zeros.
Then it converts it to form you want. It also works with numbers like 234000.
def test(number:int):
zeros=0
for i in str(number)[::-1]:
print(i)
if i=='0':
zeros += 1
else:
break
return str(number)[:-(zeros)]+'e'+str(zeros)

You are only reproducing the first non-zero digit. There can be more of them.
Also, you shouldn't count zeroes that are not part of the trailing series of zeroes, so start your loop from the end and break out of the loop.
Change:
for i in number:
if i == '0': zeros += 1
return number[0] + 'e' + str(zeros)
to:
for i in reversed(number):
if i == '0':
zeros += 1
else:
break
if zeros:
return number[:-zeros] + 'e' + str(zeros)
return number
If you are OK with using a regular expression then you can replace the loop like this:
import re
def test(number: int):
number = str(number)
zeros = len(number) - re.search(r"0*$", number).start()
if zeros:
return number[:-zeros] + 'e' + str(zeros)
return number

Related

Indexerror:::: list index out of range [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
hi this is my code and I don't know why I received this type of error
x = int(input())
n = [int(i) for i in input().split()]
middle = n[int((x - 1) / 2)
even = 0
odd = 0
for number in n:
if number % 2 == 0:
even += number
else:
odd += number
answer = even * odd + middle ** 2
print("{} x {} + {}^2 = {}".format(even, odd, middle, answer))
It produces an error as such IndexError: list index out of range because n has the minimum number of list values entered by the user.
Since your intention was for n to have more values than the minimum number of digits entered by the user, I added .range() to the list iteration.
Here is the modified code:
x = int(input("Put in a number: "))
n = [int(i) for i in range(int(input("Put in another number: ")))]
middle = n[int((x - 1) / 2)]
even = 0
odd = 0
for number in n:
if number % 2 == 0:
even += number
else:
odd += number
answer = even * odd + middle ** 2
print("{} x {} + {}^2 = {}".format(even, odd, middle, answer))
If you have any questions or need clarification, please do not hesitate to ask.

Finding the sum of numbers from x to y and the program prints the answer as "x+(x+1)....+y= (sum of # from x to y)" [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
For example, the sum of numbers from 1 to 3 would be printed as 1+2+3=6; the program prints the answer along with the numbers being added together. How would one do this? Any help is greatly appreciated as nothing I've tried has worked. I have been trying to use the sum formula to get the answer and a loop to get the numbers being added together... but with no success. Although the hint is to use for loops, but I'm not sure how to incorporate that into the program. The practice prompt also says that I can't use sum or .join functions :(, I know that would make things so much easier. Omg I'm so sorry for forgetting to mention it.
Try using this
x = 3
y = 6
for i in range(x, y+1):
opt_str += str(i) + "+"
sum += i
print(opt_str[:-1] + "=" + str(sum))
Output:
3+4+5+6=18
You can use join and list comprehension to assemble the string.
n1 = 1
n2 = 3
li = str(n1)+"".join(["+"+str(i) for i in range(n1+1,n2+1)])+"="+str(sum(range(n1,n2+1)))
print (li)
Output:
1+2+3=6
you can try this
def problem1_3(n):
return n + problem1_3(n-1) if n > 1 else 1
or try below
n = 0
sum = 10
for num in range(0, n+1, 1):
sum = sum+num
print("SUM of first ", n, "numbers is: ", sum )
output
SUM of first 10 numbers is: 55
An interesting way to do this is to print a little bit at a time. Use end='' in your prints to avoid newlines:
num = 3
sum = 0
for i in range(1,num+1):
sum += i
if i>1:
print ("+", end='')
print(i, end='')
print("=%d" % sum)
1+2+3=6
The simplest way would be using for loops and print() function
def func(x,y):
sum = 0
#Loop for adding
for i in range(x,y+1):
sum+=i
#Loop for printing
for i in range(x,y+1):
if i == y:
print(i,end = '')
else: print(i," + ",end = '')
print(" = ",sum)
The end argument to the print() function specifies what your printed string is going to terminate with, instead of the default newline character.
So for your example here,
func(1,3) Will output : 1 + 2 + 3 = 6
Here is the code:
print("Finding the sum of numbers from x to y")
print("Please specify x & y(x<=y):")
x = int(input(" x:"))
y = int(input(" y:"))
numbers = [x]
result = f"Sum: {x}"
for i in range(1,y-x+1):
numbers.append(x+i)
result += f"+({x}+{i})"
print(f"{result} = {sum(numbers)}")
output:
Finding the sum of numbers from x to y
Please specify x & y(x<=y):
x:1
y:10
Sum: 1+(1+1)+(1+2)+(1+3)+(1+4)+(1+5)+(1+6)+(1+7)+(1+8)+(1+9) = 55
output2:
Finding the sum of numbers from x to y
Please specify x & y(x<=y):
x:2
y:6
Sum: 2+(2+1)+(2+2)+(2+3)+(2+4) = 20

Why doesn't this digital root function work? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm doing a challenge on codewars, and I'm supposed to write a digital root function in Python. I can't figure out why it's not working. This is my first attempt at recursion. I would really like to wrap my head around this.
def digital_root(num):
#Check to see if num has more than one digit
if num > 9:
x = 0
z = 1
#Create an array of the digits in num
digits = [int(d) for d in str(num)]
#Convert string elements in digits[] to ints
for n in digits:
digits[x] = int(x)
x = x + 1
#Add each element in digits[] to digits[0]
for n in digits:
digits[0] = digits[0] + digits[z]
#If digits[0] has more than one digit, then run digital_root with digits[0] in the parameters
if digits[0] > 9:
digital_root(digits[0])
else:
return digits[0]
else:
return num
digital_root(15)
>> Program finished with exit code 0
There are a lot of things wrong with your function. Let's go down the list.
#Convert string elements in digits[] to ints
for n in digits:
digits[x] = int(x)
x = x + 1
This section is intended to convert the elements of digits into ints, but the elements of digits are already ints. The earlier list comprehension already produced ints:
digits = [int(d) for d in str(num)]
# ^^^^^^
The whole section is unnecessary. It's not even filling digits with the right ints; instead of calling int on the elements of digits, it calls int on the indices. Also, the loop makes no use of the loop variable n.
for n in digits:
digits[0] = digits[0] + digits[z]
This loop attempts to add all the digits together. However, z is never incremented, so this adds digits[1] to digits[0] every time. Also, even if the loop was changed to increment z, it would most likely go too far and run off the end of the list; z starts at 1, and the loop performs one iteration for each element of digits, so by the last iteration, z would be past the end of the list. Also, again, the n variable is unused.
Using digits[0] as a place to hold the sum muddles up the meaning of the digits array during the loop. It'd be better to use a separate variable (and doing so would avoid needing to start z at 1), but since Python already has a sum function, it'd be even simpler to just use sum.
#If digits[0] has more than one digit, then run digital_root with digits[0] in the parameters
if digits[0] > 9:
digital_root(digits[0])
else:
return digits[0]
This is inside the above loop, but it doesn't look like it's supposed to be; it looks like it was intended to run after digits[0] contains the sum. If so, it should be dedented (delete 4 spaces from each line). Also, since there's no return on the recursive call, the return value of the recursive call is discarded.
A corrected version of your function could look like
def digital_root(num):
if num > 9:
digits = [int(d) for d in str(num)]
total = 0
for n in digits:
total += n
if total > 9:
return digital_root(total)
else:
return total
else:
return num
A simpler solution to the challenge, taking advantage of sum, would be
def digital_root(num):
while num > 9:
num = sum(map(int, str(num)))
return num
or, keeping it recursive,
def digital_root(num):
if num < 10:
return num
return digital_root(sum(map(int, str(num))))

Regarding formatting of printed outputs (python) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have been working on the program that lists out the products (with their cost and quantity) , and they are separately stored in 3 different lists.
However, what I can't figure out how to do is , aligning of the printed outputs
while valid ==1 :
if user_choice == 's':
user_product = str(input("Enter a product name: "))
valid = 2
elif user_choice == 'l':
print ("Product" + " " + "Quantity" +" "+ "Cost")
c = 0
while c < len(product_names):
print (product_names[c] + " " + str(product_costs[c]) + " "+ str(quantity[c]))
c +=1
valid = 0
break
valid = 0
So basically I am not sure on how to actually make output on line 6 and
line 9 be aligned together because I'll be getting a disorganized output because the product names differ in length, cost and quantity differ in length too.
Can anybody teach me how to actually align them all properly so that they might
look like a table?
Thanks so much!
Here is what you wanted, exactly by the prescribed order.
n = -1 # Intentionally an incorrect value
# Ask user for the number while he/she doesn't enter a correct one
while n < 10:
n = int(input("Enter an integer number greater or equal 10: "))
# Preparation for Sieve of Eratosthenes
flags_list = ["P"] # 1st value
flags_list = flags_list * (n + 1) # (n + 1) values
flags_list[0] = "N" # 0 is not a prime number
flags_list[1] = "N" # 1 is not a prime number, too
# Executing Sieve of Eratosthenes
for i in range(2, n + 1):
if flags_list[i] == "P":
for j in range(2 * i, n + 1, i):
flags_list[j] = "N"
# Creating the list of primes from the flags_list
primes = [] # Empty list for adding primes into it
for i in range(0, n + 1):
if flags_list[i] == "P":
primes.append(i)
# Printing the list of primes
i = 0 # We will count from 0 to 9 for every printed row
print()
for prime in primes:
if i < 10:
print("{0:5d}".format(prime), end="")
i = i + 1
else:
print() # New line after the last (10th) number
i = 0
=========== The answer for your EDITED, totally other question: ===========
=========== (Please don't do it, create a new question instead.) ===========
Replace this part of your code:
print ("Product" + " " + "Quantity" +" "+ "Cost")
c = 0
while c < len(product_names):
print (product_names[c] + " " + str(product_costs[c]) + " "+ str(quantity[c]))
c +=1
with this (with the original indentation, as it is important in Python):
print("{:15s} {:>15s} {:>15s}".format("Product", "Quantity", "Cost"))
for c in range(0, len(product_names)):
print("{:15s} {:15d} {:15d}".format(product_names[c], quantity[c], product_costs[c]))
(I changed your order in the second print to name, quantity, cost - to correspond with your 1st print.)
Probably you will want change 15's to other numbers (even individually, e. g. to 12 9 6) but the triad of numbers in the first print must be the same as in the second print().
The explanation:
{: } are placeholders for individual strings / integers listed in the print statements in the .format() method.
The number in the placeholder express the length reserved for the appropriate value.
The optional > means the output has be right aligned in its reserved space, as default alignment for text is to the left and for numbers to the right. (Yes, < means left aligned and ^ centered.)
The letter in the placeholder means s for a string, d (as "decimal") for an integer - and may be also f (as "float") for numbers with decimal point in them - in this case it would be {:15.2f} for 2 decimal places (from reserved 15) in output.
The conversion from number to string is performed automatically for symbols d or f in the placeholder, so str(some_number) is not used here.
Addendum:
If you will have time, please copy / paste your edited version as a new question, then revert this question to its original state, as people commented / answered your original one. I will find your new question and do the same with my answer. Thanks!

Replacing numbers ending in 3 and 7 in a string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Write a program that generates and prints a list of n elements (n informed by the user) containing the natural numbers (starting with 1) and replacing multiples of 3 by the word 'ping', multiples of 7 by the word 'pong', and multiples of 3 and 7 by the word 'ping-pong'
Here is the code for that
result = []
number = eval(input("Enter a whole number: "))
for index in range(number):
if index % 7 == 0 and index % 3 == 0:
result.append("ping-pong")
elif index % 3 == 0:
result.append("ping")
elif index % 7 == 0:
result.append("pong")
else:
result.append(index)
print(result) == 0
Now also replaces numbers ending in 3 by the word ‘PING’ and numbers ending in 7 by the word ‘PONG’ this I am not sure how to go about doing.
I tried to make your code do what you want while doing as few modifications to it as possible.
Do NOT use eval. Ever. Bad, bad, bad eval. To cast an string to an int, use int().
Your code was starting at 0 when it was asked that it started at 1, I
changed the range.
To know the last digit, I calculated the number modulo 10, based on the clever comment by #Renuka Deshmukh. Other less clever solutions could have been to check the end of the number casted as a string, with str(index).endswith("7") or str(index)[-1] == "7", for example.
What was your print(result) == 0 trying to do? I removed the ==0.
Here is the resulting code:
result = []
number = int(input("Enter a whole number: "))
for index in range(1,number+1):
if index % 7 == 0 and index % 3 == 0:
result.append("ping-pong")
elif index % 3 == 0 or index % 10 == 3:
result.append("ping")
elif index % 7 == 0 or index % 10 == 7:
result.append("pong")
else:
result.append(index)
print(result)

Categories