2014-11-14 28 views
1

好了,所以什麼即時試圖做的是交替的字符串的其餘部分字符串中的前兩個值。我想前兩個字符交替成字符串的其餘部分在python

我有什麼是..... 「* + 123」

我要的是..... 「1 * 2 + 3」

IM肯定的答案很簡單,但我「已經摺磨我的頭在這.....我是初學者

香港專業教育學院試圖分離前兩個位置,並把它們放在不同的變量,並輪流這樣:

這是我的代碼

formula = '*+*123'  
first_part = formula[0:3]  
second_part = formula[3:len(formula_chosen)]  
print first_part  
print second_part  
expanded = '' 

for i in range(len(second_part)-1): 
    expanded = expanded + second_part[i] + first_part[i] 
print expanded 

但我最終得到的是:「1 * 2 +」

+0

意外我在變量「公式」中添加了一個額外的'*' –

+0

編輯您的帖子並將其刪除。 – IanAuld

回答

0

你是非常,在你正在嘗試做的非常具體。如果這是你正在嘗試做的練習,其中指令是,「鑑於5個字符的字符串,創建一個新的字符串,其中前兩個字符相間的最後3中一個新的字符串」,那麼上面的代碼將工作爲你在這個有限的情況下。

但是,如果您試圖解決問題,那麼獲得有關您試圖解決的問題的更多詳細信息以及爲何要解決該問題將會很有幫助。

由於en_Knight指出,該功能不會對各種輸入工作。而在計算點,一般是創建代碼,通過爲通用,足以多次與不同的輸入解決同樣的問題,使工作更容易。

一些樣式註釋:在獲取列表的各個部分時,只需要在不是0時提供開始編號,或者在不是列表的末尾提供結束編號。因此,而不是

second_part = formula[3:len(formula_chosen)]  

可以簡單的寫:

second_part = formula[3:]  

其中後:信號空白部分「獲取所有內容到字符串的結尾」。

爲了給你一個關於編寫代碼的含義的想法,所以它是一個更一般的解決方案,下面是一個函數,它描述了任意長度的字符串:將它們精確地分成兩半,然後交替字符。

def alternate_half(input): 
    output = "" 
    input_a = input[:len(input)/2] 
    input_b = input[len(input)/2:] 
    for pos, char in enumerate(input_b): 
     output += char 
     if len(input_a) > pos: 
      output += input_a[pos] 
    return output 

解釋:

  • 高清只是設置的功能,名爲alternate_half,這裏用一個參數,或者輸入值,稱爲「輸入」,也就是你在上面貼上公式的字符串。
  • input[:len(input)/2]``input[len(input)/2:] - 這些都是主要列表的切片。它使用上面的技巧 - python自動填充0或列表的末尾。它還使用了在Python中用整數進行劃分時的返回結果。因此,例如在長度爲5的字符串的情況下,len(input)/2爲2,所以input_a是前2個字符,input_b是通過字符串末尾的字符2,因此爲「123」。
  • 枚舉爲可迭代(例如字符串)中的每個項目返回一個計數器。所以enumerate("*+123")在功能上等同於[(0, '*'), (1, '+'), (2, '1'), (3, '2'), (4, '3')]。因此,我們可以使用input_a中的位置參數並附加到input_b中的相應字符。
  • 最後我們檢查一下,以確保如果input_a更短,我們不會嘗試獲取超過字符串長度的字符。因爲我們將字符串分成兩半,因此input_a永遠不會比input_b短一個字符。
0

您近了!

這裏是你的代碼工作的一個版本 - 保持一個字符去,然後砍掉結束

formula = '*+*123'  
first_part = formula[0:3]  
second_part = formula[3:len(formula)]  
print first_part  
print second_part  
expanded = '' 

for i in range(len(second_part)):#changed here 
    expanded = expanded + second_part[i] + first_part[i] 

expanded = expanded[:-1] #changed here 
print expanded 

你可能不喜歡這樣的額外的印章(你不應該)。您的算法的問題是,它沒有處理好,當事情甚至不長,監守你將一半的名單。一個更好的方式來處理,即使/奇怪與「模數」運算符

Modulo operator in Python

這裏有一個有趣的方式使用一些Python的技巧來解決這個問題,如果你想通過它來使你的方式,它可能是教育:)

formula = '*+123' 
out = '' 

for c1,c2 in zip(formula,formula[::-1]): 
    out += c2 + c1 
out = out[:len(out)/2][::-1]  

print(out) 
0

嘗試使用itertools在Python中使用iterables時值得檢查。

import itertools 

def alternate_characters(formula): 
    try: 
     if type(formula) is str: 
      operators = formula[:2] 
      operands = formula[2:] 
      iterable = itertools.izip_longest(operands, operators) 
      alt = '' 
      for tup in iterable: 
       for k in tup: 
        if k is not None: 
         alt += k 

      return alt 
    except TypeError: 
     print "Formula must be a string" 

以輸入字符串:

print alternate_characters('*+123') 
'1*2+3' 

對於非字符串輸入:

print alternate_characters(*+123) 
'TypeError: alternate_characters() argument after * must be a sequence, not int' 
+1

我強烈建議不要使用'except:'。總是試圖明確你想要捕捉什麼。 –

+0

謝謝@JordanReiter – br3w5

1

這樣的事情,使用itertools.cycle()。這適用於任何長度的字符串,第一部分,你可以決定的任何長度工作..(只是更換2具有可變)

In [35]: from itertools import cycle 

In [36]: s='*+123' 

In [37]: part1=cycle(s[:2]) 

In [38]: part2=s[2:] 

In [39]: processed_string=''.join([digit+part1.next() for digit in part2])[:-1] 

In [40]: processed_string 
Out[40]: '1*2+3' 

拆開第一部分,由它構成一個循環。循環在next()中保持循環迭代。
列表理解構造part2中每個數字的列表,並與itertools.cycle上的next()連接,稱爲part1(這使它在*和+之間交替)。
''.join()這個列表來創建一個字符串。擺脫最後一次迭代不需要的尾隨附加。

說明

In [50]: part1=cycle(s[:2]) 

In [51]: part1.next() 
Out[51]: '*' 

In [52]: part1.next() 
Out[52]: '+' 

In [53]: part1.next() 
Out[53]: '*' 

In [54]: part1.next() 
Out[54]: '+' 

In [55]: #alternates 

In [56]: # list comp 

In [57]: [digit for digit in part2] 
Out[57]: ['1', '2', '3'] 

In [58]: [digit+part1.next() for digit in part2] 
Out[58]: ['1*', '2+', '3*'] 

In [59]: # this is a list of strings and can be joined using join. 

In [60]: ''.join([digit+part1.next() for digit in part2]) 
Out[60]: '1+2*3+' 

In [61]: # this has a trailing extra character. get rid of it using slices 

In [62]: ''.join([digit+part1.next() for digit in part2])[:-1] 
Out[62]: '1*2+3' 

In [63]: #solution 

爲了避免最後一個字符的末滴,你可以構建除了最後2部分的所有字符的列表(第2部分[: - 1]),然後添加的最後一個字符第2部分(第2部分[-1])是這樣的:

In [64]: part1=cycle(s[:2]) 

In [65]: ''.join([digit+part1.next() for digit in part2[:-1]]) 
Out[65]: '1*2+' 

In [66]: ''.join([digit+part1.next() for digit in part2[:-1]])+part2[-1] 
Out[66]: '1*2+3' 

您可以將其括在這樣的函數:

In [67]: # enclose in a function 

In [68]: def process_text(text,no_of_symbols): 
    ....:  part1=cycle(text[:no_of_symbols]) 
    ....:  part2=text[no_of_symbols:] 
    ....:  return ''.join([digit+part1.next() for digit in part2])[:-1] 
    ....: 

In [69]: process_text('+*-123456',3) 
Out[69]: '1+2*3-4+5*6' 
相關問題