[SOLVED]Can't tell what's wrong here | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

[SOLVED]Can't tell what's wrong here

Trying to make a code which detects numbers in a string and prints the smallest number into it (e.g "1 + 2 = 3" and output would be 1 or none if there are no numbers). However, my output is 1 none none none 1 none none none 1. Code : S = input() a = [] for c in S: if c >= '0' and c <= '9': a.append(int(c)) print(min(a)) else: print('None')

28th Dec 2020, 11:06 PM
vlad the big boi
vlad the big boi - avatar
7 Answers
+ 5
Try this S = input() a = [] for c in S: if c >= '0' and c <= '9': a.append(int(c)) if a == []: print('None') else: print(min(a)) I placed your print(min(a)) external to your loop so it won't print on every iteration. Let the loop do the work, then place an if/else condition on list(a) to show your final result
28th Dec 2020, 11:28 PM
Rik Wittkopp
Rik Wittkopp - avatar
+ 3
Instead of...if c >= '0' and c <= '9': use c.isdigit() and take the print statement out of the loop.... Later... in a print statement do some thing like (I've not got my IDE on right now) print(min(a) if len(a) else "none") edit:- you dont even need the len (just checked), just do : print(min(a) if a else "none")
28th Dec 2020, 11:28 PM
rodwynnejones
rodwynnejones - avatar
+ 2
You can use a regular expression to detect the numbers.
28th Dec 2020, 11:31 PM
program
program - avatar
+ 2
// ζοhιπ The code is recognising that format because it will be referring to the character ordinals It does look unusual though & it was the first thing I checked
28th Dec 2020, 11:32 PM
Rik Wittkopp
Rik Wittkopp - avatar
+ 2
// Rik Wittkopp Yep that's true but we can filter a string and get numbers contained in that string (if we only want to filter)
28th Dec 2020, 11:39 PM
program
program - avatar
+ 1
// In fact, during this loop, your program didn't know "+" and "=" signs because those are not numbers but strings.
28th Dec 2020, 11:29 PM
program
program - avatar
+ 1
This code will also work for more than 1 digit numbers.. input : 111+34=145 output: 34 import re pattern=re.compile(r"\d+") my_string=input("Enter your string here : ") numbers=re.findall(pattern,my_string) if numbers: print(min(numbers)) else: print("None") https://code.sololearn.com/cYbvw33Gi0Sb/?ref=app
29th Dec 2020, 9:39 AM
Ratnapal Shende
Ratnapal Shende - avatar