当前位置: 首页>>代码示例>>Python>>正文


Python statistics.mode函数代码示例

本文整理汇总了Python中statistics.mode函数的典型用法代码示例。如果您正苦于以下问题:Python mode函数的具体用法?Python mode怎么用?Python mode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了mode函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: resetPass

def resetPass(customCommand,test=False):
	from random import sample as randomize
	from random import random
	from os.path import exists
	# Opens the Adj, Adv, and Noun files as arrays
	av = open(sys.path[0]+"/Adv").read().splitlines()
	aj = open(sys.path[0]+"/Adj").read().splitlines()
	nn = open(sys.path[0]+"/Noun").read().splitlines()
	# Just for fun, some statistics!
	totalCombos = len(av)*len(aj)*len(nn)
	combosFormatted = "{:,}".format(totalCombos)
	avLengths=[]
	for item in av:
		avLengths.append(len(item))
	ajLengths=[]
	for item in aj:
		ajLengths.append(len(item))
	nnLengths=[]
	for item in nn:
		nnLengths.append(len(item))
	from statistics import mean,median,mode
	print("-"*25+"\n"+
		  "Total adverbs: "+str(len(av))+"\n"+
		  "Total adjectives: "+str(len(aj))+"\n"+
		  "Total nouns: "+str(len(nn))+"\n"+
		  "Total possible combinations: "+combosFormatted+" (not factoring in numbers)\n"+
		  "Shortest possible passphrase length: "+str(min(avLengths)+min(ajLengths)+min(nnLengths))+"\n"+
		  "Longest possible passphrase length: "+str(max(avLengths)+max(ajLengths)+max(nnLengths)+5)+"\n"+
		  "Mean passphrase length: "+str(int(mean(avLengths)+mean(ajLengths)+mean(nnLengths)+4))+"\n"+
		  "Median passphrase length: "+str(int(median(avLengths)+median(ajLengths)+median(nnLengths))+4)+"\n"+
		  "Mode passphrase length: "+str(int(mode(avLengths)+mode(ajLengths)+mode(nnLengths))+4)+"\n"+
		  "-"*25)
	# Randomize the order of the arrays
	av = randomize(av,len(av))
	aj = randomize(aj,len(aj))
	nn = randomize(nn,len(nn))
	# Pick a random word from each randomized array
	newAdverb = av[int(random()*len(av))].capitalize()
	newAdjective = aj[int(random()*len(aj))].capitalize()
	newNoun = nn[int(random()*len(nn))].capitalize()
	# Possibly add a random number from 1 to 10,000
	if maybeNumber():
		from math import ceil
		number = str(ceil(random()*10000))
	else:
		number = ''
	# Assemble the passphrase
	newPassphrase = number+newAdverb+newAdjective+newNoun
	#################################################################### Needs attention
	print("The new passphrase will be: "+newPassphrase)
	print("Total entropy: ~"+str(int(entropy(newPassphrase))))
	if customCommand == ' {PASSPHRASE}':
		print("Password display command not found. Aborting.")
		exit()
	if not test:
		import RouterPasswording
		RouterPasswording.newPassphrase(newPassphrase)
	from os import system as execute
	execute(customCommand.replace("{password}",newPassphrase).replace("{passphrase}",newPassphrase))
开发者ID:WolfgangAxel,项目名称:Random-Projects,代码行数:59,代码来源:WifiRPG.py

示例2: find_hit_regions

def find_hit_regions(primer, alignment): #this one is for all the sequences in the alignment
    '''this is currently super inefficient... It basically does the work of primer_coverage() for every single possible
    frame in a sliding window for every sequence... If I'm ok with this I should just have this function return the
    number of mismatches for the positions which best match...  If I do that then I could have the amplicon length be
    something that was returned as well.....hmmm very tempting... I think I should do this.  what else besides amplicon
    length would this allow me to do?  I could also have it output potential mispriming sites, and then the amplicon
     length for the misprimed sites.... I could include a condition where it would print a warning if mispriming
     is likely, output a spreadsheet that tells you what sequences are likely to misprime, how big the amplicon
     for the mispriming would be...  But this mispriming would only be for these particular sequences that you are
     tyring to amplify, A much more liekly source of mispriming would just be other random genomic DNA.  A metagenome
     might be a good thing to run this, but that would really take a long time.....'''

    alignment_len = len(alignment[0])
    primer_length = len(primer)
    number_of_frames = (alignment_len - primer_length) + 1
    range_of_frames = range(0, number_of_frames)
    list_of_indexes = []
    first_indexes = []
    last_indexes = []
    frame_indexes = {}
    for frame in range_of_frames:
        frame_indexes[frame] = {}
        frame_indexes[frame]["first"] = frame
        frame_indexes[frame]["last"] = frame + primer_length

    hit_regions = {}
    for seq in alignment:
        sequences = {}
        for frame in frame_indexes:
            sequence = seq[frame_indexes[frame]["first"]:frame_indexes[frame]["last"]]
            #print(sequence)
            sequences[frame] = sequence

        number_mismatches = {}
        for key in sequences:
            number_mismatches[key] = 0
            for count, position in enumerate(sequences[key].upper()):
                #print(count, position)
                if position not in ambiguous_dna_values[primer[count]]:
                    number_mismatches[key] += 1
        indexes = frame_indexes[min(number_mismatches, key=number_mismatches.get)]
        hit_regions[seq.id] = indexes
        #print("number of sequences checked: {}".format(len(hit_regions)))
        #print("Percent complete: {}".format(len(hit_regions)/len(alignment)))
    #hit_regions = set(hit_regions)
    #print(hit_regions)

    starting = []
    ending = []
    for key in hit_regions:
        #print(key)
        starting.append(hit_regions[key]["first"])
        ending.append(hit_regions[key]["last"])
    #print(starting)
    #print(ending)
    starting = mode(starting)
    ending = mode(ending)
    return starting, ending
开发者ID:Jtrachsel,项目名称:AEM-funbuts,代码行数:58,代码来源:butcoverage.py

示例3: classify

 def classify(self, text):
     features = self.find_features(text)
     votes = []
     for c in self._classifiers:
         v = c.classify(features)
         votes.append(v)
     choice_votes = votes.count(mode(votes))
     conf = choice_votes / float(len(votes))
     return (mode(votes), conf)
开发者ID:anant14014,项目名称:TwitterNERSentimentAnalysis,代码行数:9,代码来源:SentimentClassifier.py

示例4: main

def main():
    print(stats.mean(range(6)))
    print(stats.median(range(6)))
    print(stats.median_low(range(6)))
    print(stats.median_high(range(6)))
    print(stats.median_grouped(range(6)))
    try:
        print(stats.mode(range(6)))
    except Exception as e:
        print(e)
    print(stats.mode(list(range(6)) + [3]))
    print(stats.pstdev(list(range(6)) + [3]))
    print(stats.stdev(list(range(6)) + [3]))
    print(stats.pvariance(list(range(6)) + [3]))
    print(stats.variance(list(range(6)) + [3]))
开发者ID:L1nwatch,项目名称:Mac-Python-3.X,代码行数:15,代码来源:learn_statistics.py

示例5: classify

 def classify(self,features):
     votes=[]
     for c in self._classifier:
         v=c.classify(features)
         votes.append(v)
     votes.append("pos")    
     return mode(votes)
开发者ID:rajakamraj,项目名称:Sentiment-Analyzer,代码行数:7,代码来源:Main.py

示例6: classify

 def classify(self, features):
     votes = []
     for c in self._classifiers:
         v = c.classify(features)
         votes.append(v)
         print(v)
     return mode(votes)
开发者ID:rajakamraj,项目名称:Sentiment-Analyzer,代码行数:7,代码来源:trainClassify.py

示例7: basic_stats

def basic_stats(total_data):
    mean = statistics.mean(total_data)
    median = statistics.median(total_data)
    mode = statistics.mode(total_data)
    standard_dev = statistics.stdev(total_data)

    return [mean, median, mode, standard_dev]
开发者ID:wongstein,项目名称:thesis,代码行数:7,代码来源:statistic.py

示例8: diff1

def diff1(listy):
    pie=listy
    awe=[]
    d=reduce(gcd,listy)
    for elem in listy:
        awe.append(elem/d)
    listy=awe
    new=[listy]
    old=[pie]
    for elem in listy:
        new.append(diff(new[-1]))
    for elem in listy:
        old.append(diff(old[-1]))
    new=new[0:-1]
    old=old[0:-1]
    loop=-1
    oth=0
    for elem in new:
        loop=loop+1
        if elem.count(elem[0])==len(elem):
            me=loop
            oth=1
    if oth==1:
        old=old[0:me]
        old=list(reversed(old))
        start=new[0][0]
        loop=0
        for elem in old:
            loop=loop+elem[-1]
        return(loop)
    else:
        return(mode(pie))
开发者ID:orcapt,项目名称:orca_python,代码行数:32,代码来源:OO+Scatter.py

示例9: classify

 def classify(self, features):
     votes = []
     for c in self._classifiers:
         v = c.classify(features)
         votes.append(v)
     result = mode(votes)
     return result.lower()
开发者ID:0JAdams,项目名称:TwitterMovieTracker,代码行数:7,代码来源:SentimentAnalyzer.py

示例10: vote

	def vote(self, training_set):
		votes = []
		for c in self.classifiers:
			v = c.classify(training_set)
			votes.append(v)

		return mode(votes)
开发者ID:BHouwens,项目名称:Sentiment,代码行数:7,代码来源:election.py

示例11: mode

def mode(RGB_list, count):
    ''' Gets mode element of a list given'''
    
    temp = []
    for index in RGB_list:
        temp.append(index[count])
    return statistics.mode(temp)
开发者ID:cooperb14,项目名称:hw4,代码行数:7,代码来源:effects.py

示例12: classify

 def classify(self, features):
     votes = []
     for c in self._classifiers: #c for classifiers
         v = c.classify(features) #v for votes
         votes.append(v)
     #print(votes)
     return mode(votes)
开发者ID:Ignis123,项目名称:Sentiment,代码行数:7,代码来源:sentiment.py

示例13: process_file

def process_file(filename):
    # data = np.recfromcsv(filename, delimiter=',', filling_values=numpy.nan, case_sensitive=True, deletechars='', replace_space=' ')
    with io.open(filename, "r", encoding="UTF-8") as source_file:
        data_iter = csv.DictReader(source_file)
        # data = [data for data in data_iter]
        pricelist = []
        unitlist = []
        for line in data_iter:
            pricelist.append(float(line["product_price"]))
            unitlist.append(line["OKEI_name"])
        price_med = statistics.median(pricelist)
        unit_mode = statistics.mode(unitlist)
        # df = pd.DataFrame(data)

    med_outliers = []
    mod_outliers = []

    with io.open(filename, "r", encoding="UTF-8") as source_file:
        data_iter = csv.DictReader(source_file)
        for line in data_iter:
            if line["OKEI_name"] != unit_mode:
                mod_outliers.append(line)
            if (float(line["product_price"]) / price_med) > 3:
                med_outliers.append(line)

    return price_med, unit_mode, med_outliers, mod_outliers
开发者ID:mithron,项目名称:spendhack,代码行数:26,代码来源:main.py

示例14: print_posts

def print_posts(posts, post_type, print_num):
    price_list = []

    for post in posts:
        try:
            price_list.append(float(post.price))
        except ValueError:
            pass

    print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%{}'
          '%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%'.format(post_type))

    if price_list:
        print('NUM of POSTS: ', len(posts))
        print('MEAN: ', statistics.mean(price_list))
        print('MEDIAN: ', statistics.median(price_list))
        try:
            print('MODE: ', statistics.mode(price_list))
            print('STDEV: ', statistics.stdev(price_list))
        except statistics.StatisticsError:
            pass

    for post in posts[:print_num]:
        pprint(post.price)
        pprint(post.title)
        pprint(post.carrier)
        pprint(post.description)
        pprint('www.kijiji.ca' + post.link)
开发者ID:Arephan,项目名称:kijiji_scraper,代码行数:28,代码来源:reporter.py

示例15: validate_array

    def validate_array(self, arr):
        '''
        given arr
        if mean and stdev of *arr* is close to target_mean and target_stdev,
        return true
        '''

        #print('there are {} elements'.format(len(arr)))
        mean = statistics.mean(arr)
        #median = statistics.median(arr)
        stdev = statistics.stdev(arr)
        mode = 0
        # most time we could not get *mode* from this array, pass it
        try:
            mode = statistics.mode(arr)
        except statistics.StatisticsError:
            pass
        #print('median: {:.3f}\n'.format(media))
        #print('mean: {:.3f}\nstdev: {:.3f}\n'.format(mean, stdev))
        if abs(self.target_mean[0] - mean) < self.target_mean[1] \
            and abs(self.target_stdev[0] - stdev) < self.target_stdev[1]:
            self.result_mean = mean
            self.result_stdev = stdev
            self.result_mode = mode
            return True

        return False
开发者ID:ericosur,项目名称:ericosur-snippet,代码行数:27,代码来源:validate_gaussian.py


注:本文中的statistics.mode函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。