简体   繁体   中英

Printing duplication once in python

Ciphertext is a string that I used to print the characters duplicated and their percentage of occurrence. Here is the code:

def freq_attack (ciphertext):
    store = ""
    character = ""
    non_character=""
    for i in xrange(len(ciphertext)):
        x = ciphertext[i]
        if(is_alphabet(x)):
            character +=x
        else:
            non_character +=x
    for char in character:
        count =(ciphertext.count(char)*100)/len(character)
        print char, count,"%"

the output is

a 400/7 %
s 100/7 %
a 400/7 %
a 400/7 %
e 100/7 %
a 400/7 %
w 100/7 %

You need to just count the characters, so use a collections.Counter() object :

from collections import Counter

def freq_attack(ciphertext):
    counts = Counter(ch for ch in ciphertext if ch.isalpha())
    total = sum(counts.itervalues())

    for char, count in counts.most_common():
        print char, count * 100.0 / total

Demo:

>>> freq_attack('hello world')
l 30.0
o 20.0
e 10.0
d 10.0
h 10.0
r 10.0
w 10.0

Your for loop iterates over each character in ciphertext one by one, which means that in the string hello world it'll come across the character l three times, and each time you count it. At the very least, use a dictionary to track counts for each letter.

The Counter() object is a subclass of the Python dictionary type, with some extra behaviour to make counting easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM