查找字符串中相同的相邻字符的数量

时间:2018-04-14 22:59:11

标签: python python-3.x for-loop

我有一个字符串:' AAAAATTT'

我想编写一个程序,每次计算2个值相同时计算。 所以在AAAAATTT'它会计算:

AA:4 TT:2

5 个答案:

答案 0 :(得分:2)

您可以使用collections.defaultdict。这是一个O(n)复杂性解决方案,它循环通过相邻的字母并根据条件构建字典。

您的输出将是一个字典,其中键作为重复的字母和值作为计数。

使用itertools.islice是为了避免为zip的第二个参数构建新列表。

from collections import defaultdict
from itertools import islice

x = 'AAAAATTT'

d = defaultdict(int)

for i, j in zip(x, islice(x, 1, None)):
    if i == j:
        d[i+j] += 1

结果:

print(d)

defaultdict(<class 'int'>, {'AA': 4, 'TT': 2}

答案 1 :(得分:0)

您可以使用public function emailOpenStoreTicket(Request $request) { $validatedData = $request->validate([ 'staff_email' => 'required|email', 'rec_message' => 'required|min:2', // Validate the ticket ID exists in the DB 'ticket_id' => 'required|exists:tickets,id' ]); // Grab the Ticket via Eloquent $ticket = Ticket::findOrFail($request->ticket_id); // Create the Mailable, passing in the Ticket $email = new EmailOpenTicket($ticket); $email->staff_email = $request->staff_email; $email->rec_message = $request->rec_message; Mail::to($email->staff_email)->send($email); return back()->with('success','Your email message has been sent.'); }

namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Ticket;
use App\Admin;

class EmailOpenTicket extends Mailable
{
    use Queueable, SerializesModels;

    public $ticket;
    public $staff_email;
    public $rec_message;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct(Ticket $ticket)
    {
        $this->ticket = $ticket;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->subject('New Open Maintenance Ticket')->markdown('admin.tickets.emailopenticket');
    }
}

答案 2 :(得分:0)

您可以将collections.Counter词典理解zip一起使用为:

>>> from collections import Counter
>>> s = 'AAAAATTT'

>>> {k: v for k, v in Counter(zip(s, s[1:])).items() if k[0]==k[1]}
{('A', 'A'): 4, ('T', 'T'): 2}

这是使用itertools.groupby实现此目标的另一种方法,但这个方法并不像上面的解决方案那样干净(在性能方面也会很慢)

>>> from itertools import groupby

>>> {x[0]:len(x) for i,j in groupby(zip(s, s[1:]), lambda y: y[0]==y[1]) for x in (tuple(j),) if i}
{('A', 'A'): 4, ('T', 'T'): 2}

答案 3 :(得分:0)

使用from collections import Counter string = 'AAAAATTT' result = dict(Counter(s1+s2 for s1, s2 in zip(string, string[1:]) if s1==s2)) print(result) 的一种方法可能如下:

{'AA': 4, 'TT': 2}

结果:

E_MISSING_APP_KEY

答案 4 :(得分:0)

您可以使用range方法尝试,而无需导入任何内容:

data='AAAAATTT'
count_dict={}
for i in range(0,len(data),1):
    data_x=data[i:i+2]
    if len(data_x)>1:
        if data_x[0] == data_x[1]:

            if data_x not in count_dict:
                count_dict[data_x] = 1
            else:
                count_dict[data_x] += 1



print(count_dict)

输出:

{'TT': 2, 'AA': 4}