2016-06-24 14 views

回答

2

家庭作業eh?

import re 

for i in re.findall('\d+', "Hello I can count to 4, 1 2 3 4."): 
    one_int = int(i) 
    print(one_int) 

要做到這一點沒有正則表達式,你將不得不遍歷字符串中的每一個字符,如果選中一個數字,並記住它的位置。 你找到了一個,檢查下一個數字是否正好是last_position + 1,然後將它合併到最後一個數字中,否則發出最後一個數字並記住新數字。最後,發出剩餘的記憶數字。

+0

是的,我會發布我的進展 - 但它有點亂。 :)感謝一堆。有沒有什麼辦法來處理,比如說,字符串拼接和測試? – kjf545

+0

看我的編輯,這將是一個循環中更多的邏輯,但一個有趣的難題 – sleeplessnerd

+0

所以我設法從字符串中拉出整數。有沒有辦法讓它們成爲一個列表,然後調用max來拉出最大的一個。這是迄今爲止我所擁有的。 ('):>> if string_test.isdigit(): >> print(string_test) – kjf545

0

在可能的分隔符上分割字符串,並嘗試將零件映射到int。只保留那些可以成功解析的,並找到最大值。

>>> import re 
>>> s = "Hello I can count to 4, 1 2 3 4." 
>>> parts = re.split(r"[ \t,.]", s) 
>>> ints = [] 
>>> for part in parts: 
>>>  try: 
>>>   ints.append(int(part)) 
>>>  except ValueError: 
>>>   pass 
>>> print(max(ints)) 
4 
+0

有沒有辦法做我沒有導入re?就像搜索字符串並測試它的整數。謝謝你的方式。 – kjf545

1

一號線的解決方案將是這樣的:

max(map(int, re.findall('[-+]?\d+',s))) 

卸下它:

re.findall('[-+]?\d+',s) #Regex to find all integers (including negatives) in your string "s" 
map(int, re.findall('[-+]?\d+',s)) #Converting the found strings to list of integers 
max(map(int, re.findall('[-+]?\d+',s))) #Returning the max element 
+0

這會將一個多位整數解析爲不同的數字。例如「你好42」分成4和2 – sleeplessnerd

+0

正確,忘了+ d \ d :) – Aviad

0

您可以檢查字符是否使用isdigit()功能的數字。創建字符串中所有整數的列表,然後從列表中獲取最大值。

str = "Hello I can count to 4, 1 2 3 4"<br/> 
int_list = [int(s) for s in str.split() if s.isdigit()]<br/> 
print max(int_list) 

編輯:

由於TessellatingHeckler指出這不符合標點符號工作,因爲它沒有通過isdigit()(例如 「4」)。

+0

這個在空格分割,'4'是其中一個項目,它不通過'。isdigit()'因爲逗號,所以會被忽略。與'4.'相同。它會說實際問題輸入的最大值爲3。 – TessellatingHeckler

+0

啊,你是對的。 M'bad。 – meesh

0

一個簡單的解決方案,從學生預期:

max = None 

num = list('0','1','2','3','4','5','6','7','8','9') 

for x in str: 
    if x in num: 
    if int(x) > max: 
     max = int(x) 

return max 
0

這裏是一個解決問題的功能性的方法,它也適用於數字大於9,但與底片:

def split_space(string): 
    return string.split(" ") 

def is_decimal(string): 
    return string.isdecimal() 


def number_or_none_from_string(string): 
    maybe_number = "" 
    for character in string: 
     if is_decimal(character): 
      maybe_number += character 
    if maybe_number == "": 
     return None 
    return int(maybe_number) 


def is_not_none(x): 
    return x is not None 

def max_from_string(string): 
    """assumption: all numbers are separated by space""" 
    numbers_and_none = map(number_or_none_from_string, split_space(string)) 
    numbers = filter(is_not_none, numbers_and_none) 
    maximum = max(numbers) 

    return maximum 

def max_from_string_short_version(string): 
    """assumption: all numbers are separated by space""" 

    return max(filter(is_not_none, map(number_or_none_from_string, split_space(string)))) 

phrase = "Hello I can count to 4, 1 2 3 4." 
print(max_from_string(phrase)) 
相關問題