blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
17ae9305168c752bece79fa37fe3694705d4212e
lshang0311/pandas-examples
/count_unique_values_in_a_column.py
270
3.5
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt data = np.random.choice(['sunny', 'rain', 'cloudy'], 1000, p=[1 / 4.0, 1 / 4.0, 1 / 2.0]) df = pd.DataFrame(data=data, columns=['weather']) df['weather'].value_counts().plot(kind='bar') plt.show()
92bc3143e176da8507ab815cf8e466f53f09be14
tianming05/Software-test
/hello.py
886
3.828125
4
from random import choice NAME_DB_FILE = "names.txt" # File containing names, one per line class Hello: """A simple class for generating a hello world string.""" def __init__(self, name = "World"): self.name = name with open(NAME_DB_FILE) as namedb: self.__name_list = namedb.r...
5e6e652b63d3a8b3fa1d07c0473788e33bdc5f16
sabrih146/python-java
/Quadratic Equation.py
573
3.875
4
a=input('A value') b=input('B value') c=input('C value') below=2*a # under the fraction srn=b**2 #inside the square root rod=-4*a*c rest=srn + rod rightb=-abs(b) #sets b negitive num_square = rest**0.5 # starting to add and subtract Olast=num_square + rightb Plast=rightb - num_square fresult...
cca125d7d0216ff58fc3c939e545206213eb419d
k-demir/Chat
/tests/encryption_test.py
842
3.625
4
import unittest from client.tools import Encryption class TestEncryption(unittest.TestCase): def test_encryption(self): """Tests whether the Diffie-Hellman key exchange and the encryption works or not""" e1 = Encryption() e2 = Encryption() public_key_e1 = e1.get_diffie_hellman("...
088b98c29745c052aabf346c56ff1be449835f0d
HGC-teacher/5023-OOP-scenarios
/students/main.py
1,735
4.21875
4
import grades students = [] # Creates a dictionary for a student named Michael # TODO: Change this code to create a Student object, rather than dictionary michael = {} michael['name'] = 'Michael' michael['english_mark'] = 80 michael['science_mark'] = 70 michael['mathematics_mark'] = 70 michael['completed_assessments'...
d6a4369f12a0a3caeec249617f3ceaa159b23f77
Mimmiee/Project-Euler
/5_smallest_multiple.py
443
3.90625
4
''' Find the smallest positive number that is a multiple of all the numbers 1-20. Not the fastest solution, could be solved with primes. ''' import math #Upper bound max_num = math.factorial(20) mult = True for i in range(0, max_num, + 20): mult = True for j in range(1, 20): if not i % j == 0: ...
1f6ac947a3a34b46b460afab0c5e29accd5c8b91
Mimmiee/Project-Euler
/15_lattice_paths.py
383
3.78125
4
''' Find how many paths there are in a 20x20 grid from the top left corner to the bottom right corner. ''' import math cord1 = 20 cord2 = 20 nk = 1 n = 1 k = 1 temp = cord1 + cord2 while temp > 1: nk *= temp temp -= 1 temp = cord1 while temp > 1: k *= temp temp -= 1 temp = cord2 while temp > 1: ...
1eb4d30116960299d0c0b5519abadeeffe3b7cc1
Mimmiee/Project-Euler
/27_quadratic_primes.py
1,130
3.75
4
''' Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n = 0. ''' max_count = 0 max_prod = 0 primes = {} def count_primes(a, b): prime_streak = True n = 0 while prime_streak: num = (n*...
5d7a03e476cf31a3e556254654bc80392aa39bb7
devendrakushwah/Competitive-programming-2019
/PERMPAL.py
956
3.671875
4
import collections def find_all_index(l,a): cnt=[] for i in range(0,len(l)): if(l[i]==a): cnt.append(i+1) return cnt #------------------------------------ for _ in range(int(raw_input())): s=str(raw_input()) freq = collections.Counter(s) o,e=[],[] odd=0 left,mid,...
426fd1ec6655fa42f10da110b6e1b5dbc4d2c11c
dianaanakman/DFP40203-
/labexercise1.py
1,212
3.984375
4
#diana anak man #20DDT19F1091 #Question 1a range(11) for i in range(11): print("The square of ", i, "is : ",i*i) print("") print("Process finished with exit code 0") #Question 1b limit=11 i=0 sum=0 while i<limit: if i%2==0: sum=sum+i i=i+1 print("The total of even numbers...
8ff3d902d81311a32faa6812b14b5e5932a83787
govindpandey96/govindpandey96
/7.python exercise answer.py
787
4.34375
4
#!/usr/bin/env python # coding: utf-8 # # Generators # ### Create a generator that generates the squares of numbers up to some number N. # In[1]: def gensquares(N): for i in range(N): yield i**2 # In[2]: for x in gensquares(10): print(x) # ### Create a generator that yields "n" random numbe...
8f6ef076291a8cab846db57ba3d871cb8af97ab6
achaudhri/PythonClass-2015
/HW4Test.py
1,513
3.71875
4
# Ambreen Chaudhri # HW 4 Sorting Algorithm Tests import unittest import HW4sort import random correct_order = [1,2,3,4,5,6,7,8,9,10] reverse_order = [10,9,8,7,6,5,4,3,2,1] not_list = 210 not_sorted = [7,4,5,9,2,3,6,8,10,1] random_list = random.sample(range(1,11),10) class sortTest(unittest.TestCase): def test_qu...
9ff964c3b6b7341c3a919549d3b8ed6fe7c3df24
tha-dance/software-algo
/KNN/knn.py
1,927
4.03125
4
''' This program achieves multi-class classification using KNN ''' from sklearn.datasets import load_iris # IRIS dataset is a pre-defined dataset in sklearn from sklearn.cross_validation import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn import metrics import matplotlib.pyplot as p...
6cff5de83ba3dba8ea6b48de1fe45c32e2cb239f
Eleanor-Engineer/python_practice
/credit_card_calc.py
3,279
4.28125
4
def check_card_input(card_no,check_no_entered): if (check_no_entered is not 'y') and (check_no_entered is not 'n'): return 'Please use the funciton like this: credit_card_calc( [credit card number, with or without the check number], [y/n to indicate if it includes the check number]' elif len(str(card_no...
3909b8b1b0c29ea21e686469e156503f5ffcdf93
notBroman/AdventOfCode_2020
/python/10/day10_2.py
1,055
3.796875
4
# notBroman # count the differences between the elements of the list after it is sorted # how many differences are 1, 2 and 3 # return the profuct of the amuont of differences that are 1 and 3 import fileinput def get_jolts(): data = list(fileinput.input()) for i in range(len(data)): data[i] = data[i...
83c04450560a3e95c4b23102ddb998d2671027e2
notBroman/AdventOfCode_2020
/python/06/day6_2.py
1,457
3.703125
4
# notBroman # there is a customs declaration sheet with 26 questions (a-z) # you note down the questions groups answer yes to # for each group a question counts once at most and only if everyone picked it # groups are split by '\n\n' # people in those groups are split by '\n' # find the total number of questions that w...
67ac9a0282cf54e04071ece60930f6fe934ecc14
Shawnmhy/BEProject
/venv1/lib/python3.6/site-packages/searching/sequence/sequence_search_algorithm.py
2,104
4.03125
4
"""A base class for sequence-based search algorithms.""" from abc import abstractmethod from typing import Callable from searching.search_algorithm import SearchAlgorithm from searching.types import Number, OptionalNumber, Sequence class SequenceSearchAlgorithm(SearchAlgorithm): """An abstract base class for...
61de1ec9e88fffe7269f159aed265309824246fd
Shawnmhy/BEProject
/venv1/lib/python3.6/site-packages/searching/sequence/algorithms/jump_search.py
2,345
4.125
4
"""An implementation of jump search.""" from searching.complexity import Complexity from searching.types import Sequence, Number, OptionalNumber from ..sequence_search_algorithm import SortedSequenceSearchAlgorithm class JumpSearch(SortedSequenceSearchAlgorithm): """ An implementation of the jump search alg...
1358a7e4cc5820f6d748e84639797469a0dacc06
Shawnmhy/BEProject
/venv1/lib/python3.6/site-packages/searching/complexity.py
1,073
3.53125
4
"""A generalization of runtime / space complexity.""" # TODO: isnt there a Python feature that implements this boilerplate automatically? class Complexity(object): """A container for complexity analysis properties of algorithms.""" def __init__(self, worst: str=None, avg: str=None, best: str=None) -> None: ...
e6903da7f9f0cc88e51ff32fa2b150076023a98f
natansalda/days_between_dates_python
/calculation.py
2,637
4.40625
4
def isLeapYear(year): if year % 400 == 0: return True if year % 100 == 0: return False if year % 4 == 0: return True else: return False def daysInMonth(year, month): if month == 1 or month == 3 or month ==5 or month == 7 or month == 8 or month == 10 or month == 1...
a15972be2eaea0ce636dcd0a068271684c60a999
Fabricio-Lopees/computer-science-learning
/exercises/01.python-for-everybody/chapter08/exercise01.py
760
4.21875
4
# Write a function called chop that takes a list and modifies it, removing the first and last elements, and returns None. def chop(array): array.pop() array.pop(0) first_array = [1,2,3,4,5] print('First array before:', first_array) result = chop(first_array) print("Result: ", result) print('First array after:', f...
8adc53ad602ffd0bcc8e68d2edd3a6bd817230bd
Fabricio-Lopees/computer-science-learning
/exercises/01.python-for-everybody/chapter08/exercise06.py
411
3.9375
4
array = [] def evaluate_numbers(): number = input("Enter a number: ") if number.lower() == 'done': if len(array) == 0: print('Maximum: None') print('Minimum: None') else: print('Maximum: ',max(array)) print('Minimum: ',min(array)) else: try: array.append(float(number)) evaluate_numbers() ...
fd9c0240cf63143fa5a8c7d9c090b38ff149d709
Fabricio-Lopees/computer-science-learning
/exercises/01.python-for-everybody/chapter11/ex02.py
600
4.21875
4
# Exercise 2: Write a program to look for lines of the form: New Revision: 39772 # Extract the number from each of the lines using a regular expression and the findall() method. Compute the average of the numbers and print out the average as an integer. import re; file_name = input('Enter a file name: '); file = open(...
79c233a64d1e8c851691803af698b3bf5987210a
Fabricio-Lopees/computer-science-learning
/exercises/01.python-for-everybody/chapter05/exercise02.py
431
4.125
4
maximum = 0; minimum = 0; guard = None; while guard != "done": try: number = input("Enter a number: ").lower() if number == "done": print("Highest number entered: ", maximum) print("Lowest number entered: ", minimum) guard = number else: number = float(number) if number > maximum: maximum = ...
6c2d9a2b105abe7386b702afb56388009a82c487
Fabricio-Lopees/computer-science-learning
/exercises/01.python-for-everybody/chapter10/ex03.py
1,212
4
4
# Exercise 3: Write a program that reads a file and prints the letters in decreasing order of frequency. Your program should convert all the input to lower case and only count the letters a-z. Your program should not count spaces, digits, punctuation, or anything other than the letters a-z. Find text samples from sever...
28ad764eb14c86beef93e4b4c916088c932d705b
Fabricio-Lopees/computer-science-learning
/exercises/01.python-for-everybody/chapter08/ex05.py
822
4.09375
4
# Exercise 5: Write a program to read through the mail box data and when you find line that starts with “From”, you will split the line into words using the split function. We are interested in who sent the message, which is the second word on the From line. # From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 # Y...
a93592d0d7247d96416ae647d3bf34527ac98e1a
Fabricio-Lopees/computer-science-learning
/exercises/01.python-for-everybody/chapter03/ex02.py
564
4.09375
4
# Exercise 2: Rewrite your pay program using try and except so that your program handles non-numeric input gracefully by printing a message and exiting the program. The following shows two executions of the program: # Enter Hours: 20 # Enter Rate: nine # Error, please enter numeric input # Enter Hours: forty # Error, ...
9c0be3aa5ff4cf7a38d4e97edeb8a904204f12e7
Fabricio-Lopees/computer-science-learning
/exercises/01.python-for-everybody/chapter06/ex03.py
322
3.921875
4
# Exercise 3: Encapsulate this code in a function named count, and generalize it so that it accepts the string and the letter as arguments. car = 'chevrolet chevette'; def count(string, letter): count = 0; for x in string: if x == letter: count = count + 1; return count; result = count(car, 't'); print(resul...
0d81200257051c9391222961e2a72af266dc26a6
anand-g-2/testrepo
/barplot.py
341
3.546875
4
import matplotlib.pyplot as plt import numpy as np objects='Python', 'C', 'C++', 'Java' #x_pos = np.arange(len(objects)) no_of_students = [10,8,6,4] plt.bar(objects, no_of_students, align='center',alpha=0.8) #plt.xticks(x_pos, objects1) plt.ylabel('Number of students') plt.title('Programming language u...
58ae6f732e310ebd214bff3a07e56f2c035dca26
Jeel-Agrawal/ShapeAI-Python_and_Network_Security_Bootcamp
/Project 2.py
375
4.25
4
# Write a program in python to generate hashes of string data using 3 algorithms from hashlib. import hashlib str_data = input("Enter your name : ") result1 = hashlib.sha256(str_data.encode()) print(result1.hexdigest()) result2 = hashlib.sha384(str_data.encode()) print(result2.hexdigest()) result3 = hashli...
b8264372b8f92406c7d56409c3cb513a81e1f962
m-tanner/PacmanCoins
/src/argument_parser.py
802
3.828125
4
"""Parses user input given in command line at runtime or list provided as an argument.""" import argparse class ArgumentParser: def __init__(self, list_of_args: list = None): self._parser = argparse.ArgumentParser(prog="PROG", prefix_chars="-/") self._add_arguments() self._list_of_args = l...
25cbbe90f78ae4ee0f4cfae306a5cdf0bbd27c2f
vinusankars/DoG-based-edge-detection
/A1Q1.py
2,460
3.625
4
#@author: S. Vinu Sankar #@date : Sept 2 #EE645, Assignment 1, Q1 #Python 3.6 and supported libraries import numpy as np import cv2 from matplotlib import pyplot as plt #Function to create gaussian filter def gaussian(std, size=9): #std is standard deviation, size is filter size filter = np.zeros((size, size)) su...
ce8ed90c3a7d2e7edc6ffae20154569dd7c1c705
VyunSergey/Euler
/Point2D.py
2,571
3.59375
4
class Point2D(object): def __init__(self, dx, dy): self.x = dx self.y = dy def __str__(self): return '(' + str(self.x) + ', ' + str(self.y) + ')' def x_eq(self, other): return self.x == other.x def y_eq(self, other): return self.y == other.y def __eq__(sel...
6cdb3949f6efdef6ef6da2df022f5e39284abe7d
za3k/short-programs
/quiz
754
3.796875
4
#!/bin/python3 """ Usage: quiz FILE.csv Interactively prompt the user to fill out a questionnaire. Reads the questions and writes the results to a CSV. Intended use is for daily, weekly, etc logging of something. """ import csv, io, readline, subprocess, sys if __name__ == '__main__': if len(sys.argv) != 2: ...
fc196cf01cfbf01634090ee34d2fc622d4959caf
shekolla/python_problems
/sum_of_arr_using_recursion.py
477
3.90625
4
''' Solution for sum of arr using recursion ''' # To import everything use '*' from python_2_3_compatibilty import (int, map, input) ''' @input an array[] @returns number ''' def addTwoNumbers(arr): # Base condition if (len(arr) == 1): return arr[0] return arr[0] + addTwoNumbers(arr[1:]) if ...
cfaa6af00dad34d004deb648ec0eb15045a44e9e
qefen/udp_service
/Pruebas Python/len_function.py
366
3.96875
4
#Programa que recibe una lista y retorna el tamaño de esta fruits=["Banana","Apple","Watermelon","Lemond"] numbers=[1,2,3,4,5,6,7,8] def my_len(list): count=0 for i in list: count=count+1 return count print("Cantidad de datos en la lista friuts : "+str(my_len(fruits))) print("Cantidad de datos ...
9d3169355b6da55b99e0912d46e82c455e0a67a7
Cerberus270/calculo_pi
/calculo_pi_problema_basilea.py
203
4.0625
4
import math six=6 N=input("Ingrese el numero de iteraciones con el que desea encontrar el valor de pi=> ") s=0 for i in range(0,N): s=(1/(math.pow(1+i,2)))+s pi=math.sqrt(six*s) #print(s) print(pi)
0b63fc238fe0682948b177f542759464cba44c47
catalinc/codeeval-solutions
/src/python/simple_or_trump.py
738
3.59375
4
import sys def eval_hand(card1, card2, trump): if card1[-1] == trump and card2[-1] != trump: return card1 if card2[-1] == trump and card1[-1] != trump: return card2 v1 = card_value(card1) v2 = card_value(card2) if v1 > v2: return card1 if v2 > v1: return card2 ...
d45a400ab00e82aa499f174439acbf4e3d910924
catalinc/codeeval-solutions
/src/python/commuting_engineer.py
1,551
3.84375
4
import sys import re import math # Solution to https://www.codeeval.com/open_challenges/90/ def shortest_path(locations): path = [] while locations: if not path: path.append(locations.pop(0)) else: min_dist = sys.maxint nearest = None for index,...
228ff1ba690469f57b066d8def3de435c7732c63
catalinc/codeeval-solutions
/src/python/longest_word.py
601
3.96875
4
import sys def longest_word(s): words = s.split(' ') return first_max(words, key=lambda w: len(w)) def first_max(iterable, key=None): item, max_value = None, None for x in iterable: if key: value = key(x) else: value = x if item is None or max_value < va...
f621f0c7a0dfe9b8ce025d221ca9a4924b487fd4
fanxiao168/pythonStudy
/AIDStudy/01-PythonBase/day17/exercise07.py
529
4.25
4
''' 练习3: 自定义生成器函数 my_enumerate, 实现下列效果 list01 = ['无忌','翠山','翠翠'] for item in enumerate(list01): print(item) # ''' def my_enumerate(iterable_target): index = 0 for item in iterable_target: yield (index, item) index += 1 list01 = ['无忌', '翠山', '翠翠'] for item in my_enume...
a51b0661869528a660514e4714069d103d06fcbc
fanxiao168/pythonStudy
/AIDStudy/01-PythonBase/day05/homework/homework2.py
264
3.71875
4
# 2.在控制台输入一个字符串 判断是否回文 # 判断规则正向与反向相同 # 上海自来水来自海上 msg = input('请输入一个字符串:') # 判断是否为回文 if msg == msg[::-1]: print('是回文') else: print('不是回文')
8597e3c09367f4b8ce8fa394722bb949802aac92
fanxiao168/pythonStudy
/AIDStudy/01-PythonBase/day07/demo05.py
626
4.03125
4
''' 函数:表示一个功能 参数:使用功能时提供的信息 ''' # 做功能 def attack(count): ''' 攻击敌人 :param count: int 攻击次数 :return: ''' for i in range(count): print('左钩拳') print('右钩拳') print('黑虎掏心') print('天马流星拳') print('临门一脚') # ... # 用功能 # 函数名保存的是对应功能的代码地址 print(attack) # 当...
247bbbe2fbd85b093a947ddf9eb6a2babaaae3ad
fanxiao168/pythonStudy
/AIDStudy/01-PythonBase/day13/demo03.py
759
3.875
4
# 老张开车去东北 day11/demo06.py # 需求变化: 坐飞机 # 坐火车 # 骑车 class Person: def __init__(self, name): self.name = name def go_to(self, postion, type): ''' :param postion:地名 :param type: 去的方法 :return: ''' print('去' + postion) # 判断怎么走 ...
de57a3ca6af7d803b98953fa67a6a2c6166eefa2
fanxiao168/pythonStudy
/AIDStudy/01-PythonBase/day06/demo02.py
1,146
4.1875
4
''' 列表推导式 快速的将可迭代对象变成列表 ''' list01 = [10, 1, 15, 5, 6, 7] # 将list01中的每一个数加一放到list02中 list02 = [] for item in list01: list02.append(item + 1) print(list02) # 从可迭代对象list01中获取元素 # 将元素带入到前面的表达是item+1 # 将结果保存到列表 继续从list01获取下一个元素 直到没有元素为止 list03 = [item + 1 for item in list01] print(list03) list04 = [] for item in lis...
3ccd900d23763c53b7e69d8c3d3d5658c33c249e
fanxiao168/pythonStudy
/AIDStudy/01-PythonBase/day02/exercise06.py
565
3.609375
4
# 在控制台录入一个四位数 # 计算每一位相加的和 # 显示结果 # 1234 --> 1+2+3+4 --> 10 num = int(input('请输入4位的整数:')) # 方法1 # 1234 % 10 -> 123 4 ge = num % 10 # 1234 // 10 -> 123 % 10 -> 12 3 shi = num // 10 % 10 # 1234 // 100 -> 12 % 10 -> 1 2 bai = num // 100 % 10 # 1234 // 1000 -> 1 qian = num // 1000 result = ge + shi + bai + qian print('方法...
2dd17ae8bfcd170e9a609a89df48a56ad585efc5
fanxiao168/pythonStudy
/AIDStudy/02-DateStruct/day01/linklist.py
3,171
4.09375
4
''' linklist.py 功能:使用节点作为数据元素的生成器,对数据元素之间的关系进行构建和操作 重点代码 ''' # 创建节点类 class Node: ''' 包含一个简单的数字作为数据 next 构建关系 ''' def __init__(self, val, next=None): self.val = val # 有用的数据 self.next = next # 节点关系 ''' 1.构建节点间关系 2.在节点中存储数据 3.对但链表进行节点操作 ''' # 但链表的类 class LinkList: ''' 思...
7884c50a2710d54512f1b1b10e3db0f6d133809f
fanxiao168/pythonStudy
/AIDStudy/01-PythonBase/day10/exercise02.py
1,336
3.875
4
# 创建Student类 # __init__ # name age score # print_self # 输出 name age score class Student: def __init__(self, name, score, age): self.name = name self.age = age self.score = score def print_self(self): print(self.name, self.age, self.score) # 创建一个列表 在列表中保存3条学生记录 # stu01 =...
5d849d02187ea9dc2295a92c511d1f0e97b22d56
fanxiao168/pythonStudy
/AIDStudy/01-PythonBase/day17/demo03.py
675
3.78125
4
''' yield ----> 生成器函数 练习:exercise05.py exercise06.py exercise07.py exercise08.py ''' class MyRange: def __init__(self,stop_value): self.__stop_value = stop_value def __iter__(self): number = -1 while number < self.__stop_value - 1: number...
fa2bbea5fd47dd02f2f9b75d76e8a3b465dddf25
fanxiao168/pythonStudy
/AIDStudy/01-PythonBase/day04/demo02.py
133
3.75
4
# for 循环嵌套 # 外层循环执行一次 内层循环执行一遍 for i in range(3): for j in range(3): print(i, j)
2d2e6d62a5adbbd398ccd607999d8de30346157c
fanxiao168/pythonStudy
/AIDStudy/01-PythonBase/day05/exercise05.py
404
4.03125
4
# 在控制台获取所有学生的成绩(循环 一个一个录入) # 如果录入空字符串 停止 # 输出最高分 最低分 和平均分 scores_list = [] while True: str_score = input('请输入成绩:') if str_score == '': break score = int(str_score) scores_list.append(score) print(max(scores_list)) print(min(scores_list)) print(sum(scores_list)/len(scores_list))
5e23673a0c6b8b409fa352ff222397eee3d4cea2
fanxiao168/pythonStudy
/AIDStudy/01-PythonBase/day02/exercise04.py
358
4.03125
4
# 练习: # 在控制台输入分钟 # 再输入小时 # 再输入天 # 计算总秒数 # 总秒数 = 分*60 + 时*3600 + 天*24*3600 # 输出结果 minute = int(input('请输入分钟:')) hour = int(input('请输入小时:')) day = int(input('请输入天数:')) result = minute * 60 + hour * 60 * 60 + day * 24 * 60 * 60 print('总秒数为:', result)
58251a5408d5997a182c5c6e6ea6395a1d1c46ba
fanxiao168/pythonStudy
/AIDStudy/01-PythonBase/day03/demo05.py
1,012
3.96875
4
''' if语句语法格式 ''' a = 10 b = 10 # b = 11 # b = 9 if a > b: # 如果不满足向下执行 # 满足条件a>b执行的代码 print(最大的数是a) # 不报错原因在下方 elif a == b: # 如果不满足向下执行 # 满足条件 a == b 时执行的代码 print('a和b相等') elif a < b: # 如果不满足向下执行 # 满足条件 a<b时执行的代码 print('最大的数时b') # else中如果没有必须执行的代码 可省略 else: pass # 占位 填充语法空白 # 选择语句执行的...
d67a93c699d4bfa5abec79a0bb6d7a7d6bb7bc9c
fanxiao168/pythonStudy
/AIDStudy/01-PythonBase/day04/homework/demo05.py
336
3.515625
4
''' 字符串格式化 ''' student = '麦奇' number = 1 age = 18 print('第' + str(number) + '位同学的姓名为' + student + ',年龄为' + str(age)) print('第%d位同学的姓名为%s,年龄为%d' % (number, student, age)) name = '哪吒' age = 3 score = 99.9 print('我叫:%s,年龄%d岁,成绩为%.2f' % (name, age, score))
42af92e18ee3c1a96cd379e93e0ad17c462c6fb4
fanxiao168/pythonStudy
/AIDStudy/01-PythonBase/day18/day17_exercise/exercise01.py
1,583
3.8125
4
# 3.创建敌人类(姓名,血量,攻击力,防御力) # 创建敌人列表,存储若干敌人 # ——-- (1)在敌人列表中查找所有死人 # ---- (2)在敌人列表中查找血量最大的敌人 # ---- (3)在敌人列表中查找所有敌人姓名与攻击力 class Enemy: def __init__(self, name, hp, atk=None, defense=None): self.name = name self.hp = hp self.atk = atk self.defense = defense enemy_l...
a35b885d411b3d03d1c04346443fd072c6c26100
fanxiao168/pythonStudy
/AIDStudy/01-PythonBase/day17/demo04.py
425
3.9375
4
''' 生成器表达式 练习:exercise09.py ''' list01 = [34, 4, 'a', 'b', 1.5, 1.8, True, False] # 生成器函数:为其他人提供功能 def find01(): for item in list01: if type(item) == str: yield item re = find01() for item in re: print(item) # 生成器表达式:为自己提供功能 re = (item for item in list01 if type(item) == str) f...
055237dfe2b023bdeed87068cb4c09364d5b8060
fanxiao168/pythonStudy
/AIDStudy/01-PythonBase/day18/demo05.py
1,006
3.96875
4
''' 装饰器 练习:exercise04.py ''' # def print_func_name(func): # def wrapper(): # print(func.__name__) # 打印函数名称 # func() # 调用函数 # # return wrapper # # # @print_func_name # def say_hello(): # print('hello') # # # # 拦截:新功能 + 旧功能 # say_hello = print_func_name(say_hello) # # # def say_goo...
7f520ecbf07190f81fe861a08deaf5a5f4ee1c62
fanxiao168/pythonStudy
/AIDStudy/01-PythonBase/day04/homework/exercise06.py
461
4
4
# 1.在控制台获取一个字符串 # 打印这个字符串的每一个字符的编码值 # 字--->数 ord('a') # 数--->字 chr(97) str = input('请输入文字:') for ch in str: print(ord(ch)) # 2.在控制台重复录入编码值 将编码值转为字符打印 # 如果录入的是空字符串 则退出程序 while True: str2 = input('请输入编码值:') if str2 == '': break code_value = int(str2) print(chr(code_value))
e3b87e2905727252e0e22ff41fd14054bb48eac8
fanxiao168/pythonStudy
/AIDStudy/02-DateStruct/day03/bitree.py
1,944
3.859375
4
''' bitree.py 二叉树的实现 思路分析: 1. 使用链式存储,Node表达一个节点(值,左连接,右链接) 2. 分析遍历过程 ''' # 二叉树节点 class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right # 二叉树遍历 class Bitree: # 传入树根 def __init__(self, root): self.root = root ...
02bf4a259258244257b464da4813331807398ef5
fanxiao168/pythonStudy
/AIDStudy/01-PythonBase/day05/demo04.py
1,200
4
4
list01 = ['三丰', '翠山', '无忌'] # 把list01中存储的地址赋值给list02 list02 = list01 list01[0] = '张三丰' print(list02[0]) # 张三丰 list01 = [800, 900, 1000] list02 = list01 list03 = list01 list01[0] = '八百' print(list02[0]) # 八百 list03 = '九百' print(list02[0]) # 八百 list01 = [800, 900, 1000] list02 = list01[:] list01[0] = '八百' print(list...
06a774dbf9933d04c6f2f7f7e90b7610f915464e
fanxiao168/pythonStudy
/AIDStudy/01-PythonBase/day06/demo03.py
1,099
4.34375
4
''' 元组的基本操作 ''' # 创建元组 tuple01 = () # 空元组 tuple01 = tuple() print(tuple01) tuple02 = (0, 1, 'nihao', True) print(tuple02) # 预留空间的存储机制(列表)--->按需分配的存储机制(元组) list01 = ['a', 'b'] tuple02 = tuple(list01) print(tuple02) list02 = list(tuple02) print(list02) tuple02 = ('a') # 不是元组 print(type(tuple02)) # <class 'str'> tup...
208979b4e74468ee824d6fede567a685803b8961
fanxiao168/pythonStudy
/AIDStudy/01-PythonBase/day05/demo03.py
1,242
4.125
4
''' 列表的基础操作 ''' # 1.创建列表 # 空列表 # list01 = [] # list(可迭代对象) 使用可迭代对象快速创建列表 list01 = list() print(list01) # 具有值的列表 list02 = ['shibw', 18, True, [1, 2, 3]] print(list02) list02 = list(range(4)) print(list02) list02 = list('我是小妖怪') print(list02) # 增加 # 需要借助列表的相关函数 # 追加元素 append() # 向列表末尾添加一个元素 list02 = list(range(4)) #...
70402d0ab2291a9db3e74730bb4041f56da7cb69
mariam234/cs181-s21-homeworks
/hw1/T1_P4.py
3,770
3.5625
4
##################### # CS 181, Spring 2021 # Homework 1, Problem 4 # Start Code ################## import csv import numpy as np import matplotlib.pyplot as plt import math csv_filename = 'data/year-sunspots-republicans.csv' years = [] republican_counts = [] sunspot_counts = [] with open(csv_filename, 'r') as csv_...
f66ac68f4cc6a4a4f039b45c441d48e594939197
trhmc/python-hw
/Python/Lab4.py
1,908
3.84375
4
##Lab04 Required Questions ## ######### # Lists # ######### # RQ1 def cascade(lst): """Returns the cascade of the given list using recursion. >>> cascade([1, 2, 3, 4]) [1, 2, 3, 4, 4, 3, 2, 1] """ if not lst: return [] else: return [lst[0]] + cascade(lst[1:]) + [lst[0]] # RQ2...
d6afbd70158af4a8c80d10eb1729a3eefc1b7a1d
L-Ezray/zpp
/3.py
237
3.75
4
a = None while True: a = int(input('请输入一个数字:')) if a == 0: continue elif a > 0 and a < 100: print('命运给予我们的不是失望之酒,而是机会之杯'*a) elif a >= 100: break
986c262e5cf79aa454af4d2de25a50b056637705
L-Ezray/zpp
/5.py
88
3.78125
4
a = 1 while a <= 100: if a%7==0 and a%5!=0: print(a) a+=1 print('over')
5de17209ba726ba4ac9cb14f2748c9e58024d5c3
ammaraskar/benchmarks
/performance/benchmarks/bm_threading.py
2,624
3.59375
4
"""Some simple microbenchmarks for Python's threading support. Current microbenchmarks: - *_count: count down from a given large number. Example used by David Beazley in his talk on the GIL (http://blip.tv/file/2232410). The iterative version is named iterative_count, the threaded ve...
7a72ecd22c359477f0953e4c6249c17d63e28eb2
IgorPVidal/Preditor_IC
/views/view.py
4,568
3.84375
4
import streamlit as st import plotly.express as px # talvez usar tkinter? #import tkinter as tk #from tkinter import ttk # OBSERVAÇÃO: Aparentemente Streamlit não reconhece algumas tipagens do Pandas, como 'category' # no exemplo herdou de tkinter. devo fazer o mesmo com streamlit? class View(): def __init__(sel...
58dfcac4a7f6487d7594d1a4ddb2740816f232b0
DumbMachine/CS6-Py
/EXP3/6.py
160
4.03125
4
mon = int(input("enther the integer for month")) year = int(input("enther the integer for year")) from calendar import monthrange print(monthrange(year, mon))
666db91703b861a114c4a4754cc65a9e5abc986b
DumbMachine/CS6-Py
/NumPY 2/4.py
253
3.84375
4
import numpy as np array1 = np.array([0, 10, 20, 40, 60, 80]) print("Array1: ",array1) array2 = [10, 30, 40, 50, 70] print("Array2: ",array2) print("Unique values that are in only one (not both) of the input arrays:") print(np.setxor1d(array1, array2))
159d735680b7dc416145ecb43e9edf24c5d170b0
DumbMachine/CS6-Py
/EXP6/exp6_4.py
231
3.984375
4
import re fname = input("Enter file name: ") num_words = 0 with open(fname, 'r') as f: for line in f: words = re.split(r'(,|\s)\s*', line) num_words += len(words) print("Number of words:") print(num_words)
95ebb86c31fc5918e22c50828da43c3f8a90ee36
DumbMachine/CS6-Py
/NumPY/2.py
172
3.828125
4
import numpy as np x = np.random.random((5,5)) print("Original Array:") print(x) xmin, xmax = x.min(), x.max() print("Minimum and Maximum Values:") print(xmin, xmax)
57fb07d39cc6ff24f33541ead8cc60fa26ab0641
DumbMachine/CS6-Py
/NumPY 2/6.py
204
3.546875
4
import numpy as np first_names = ('Margery', 'Betsey', 'Shelley', 'Lanell', 'Genesis') last_names = ('Woolum', 'Battle', 'Plotner', 'Brien', 'Stahl') x = np.lexsort((first_names, last_names)) print(x)
bff8b21ad4ef5aabf92b8f2a3d21794161792cea
moshun8/IS211_Assignment4
/search_compare.py
5,720
3.828125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """Week 4 Search Compare""" import random import time def sequential_search(a_list, item): start = time.time() pos = 0 found = False while pos < len(a_list) and not found: if a_list[pos] == item: found = True else: ...
c5838df4fcd8a980e6c078bf10b7765b53cd4ff1
Wordz278/animal
/cat.py
324
3.78125
4
from animal import Animal class Cat(Animal): def __init__(self, name, sounds): super().__init__(name, sounds) def food(self): print(self.name + " eats") def sound(self): print(self.sounds,"meows") print("==========Cat==============") cat = Cat("Stormy", "Cat") cat.food() cat.sou...
0fa66387a32fccb92a972727cf1fa4f5d723f9e2
Abhinavnj/leetcode-solutions
/product-of-array-except-self.py
928
3.703125
4
def productExceptSelf(nums): """ nums: List[int] rVal: List[int] """ numsLen = len(nums) output = [1] for i in range(numsLen - 1): output.append(output[-1] * nums[i]) rightProd = 1 for i in reversed(range(numsLen)): output[i] *= rightProd rightP...
2c3f77fa2c692b2b8bce2d4bd3bb3b74022d0149
Abhinavnj/leetcode-solutions
/find-minimum-in-minimum-sorted-array.py
785
4.03125
4
def findMin(nums): """ nums: List[int] rVal: int """ # If array is not rotated if nums[-1] >= nums[0]: return nums[0] # The inflection point is the point where the array changes # from each consecutive element being less than the one before # to the next element being l...
6d29df3da6f39f96556e81e334bd28ce5bea9259
popotam/mooc
/mitx_6_00x/midterm1/midterm1.py
2,206
3.921875
4
import itertools def laceStrings(s1, s2): """ s1 and s2 are strings. Returns a new str with elements of s1 and s2 interlaced, beginning with s1. If strings are not of same length, then the extra elements should appear at the end. """ return "".join([ element for element in itertoo...
2bac0b96cde391dcc7f9897dae4fe571993eaf4b
popotam/mooc
/mitx_6_00x/final/final.py
8,185
3.59375
4
import pylab import math import random class Location(object): def __init__(self, x, y): """x and y are floats""" self.x = x self.y = y def move(self, deltaX, deltaY): """deltaX and deltaY are floats""" return Location(self.x + deltaX, self.y + deltaY) def getX(se...
62692ec92f96cc1edd857a2ad5f664e137c44544
DeviNoles/COP4521P1
/pascals.py
1,081
3.65625
4
def driver(): global pyramidArray global rowIndex global rowCount pyramidArray = [] rowIndex = 1; print("Enter the number of rows ", end='') rowCount = input() #print(rowCount) buildPyramid(int(rowCount)+1) printPyramid() def buildPyramid(rc): global pyramidArray for i in...
4c4605877ca96e9e90f676e57851ced990e9f48a
hashimreja/machine-learning
/Datapreprocessing/preprocessinghr.py
973
3.609375
4
#importing libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt #reading file data = pd.read_csv('data.csv') data.head() X = data.iloc[:,:-1].values y = data.iloc[:,3].values #using imputer to handle missing values from sklearn.preprocessing import Imputer imputer = Imputer(missin...
cfc0addf7a76001d27cb7c32dd2fbda0959d598c
deriggi/LCOM
/domain.py
1,810
3.953125
4
import random import math class Company(object): MAX_COMPANY_SIZE = 10000; ASSESSMENT_SCORE_SIZE = 25; def __init__(self): self.size = math.floor(random.random()*Company.MAX_COMPANY_SIZE) self.assessment_scores = [] # assigne random normal scores to the self assessment def assign_assessment_scores(self): ...
5a9e5022e9dd8c28d25e132e75d66158852539f2
Mustafa017/python-programs-
/algorithm lab.py
404
3.953125
4
# -*- coding: utf-8 -*- """ Created on Wed Jan 25 22:31:16 2017 @author: mustafa """ def binary_converter(n): if(n == 0): return "0" elif(n < 0): return "Invalid input" elif(n > 255): return "Invalid input" else: ans="" while(n>0): n=n/2 remainder=n%2 ...
e68d07de7e62e716f915a32b8e2ea3cd04ae76dd
Mustafa017/python-programs-
/Stacks and Queue.py
1,545
3.875
4
# -*- coding: utf-8 -*- """ Created on Sat Feb 18 13:39:47 2017 @author: mustafa """ import sys,collections class Solution: def __init__(self): self.myStack = list() self.myQueue = collections.deque([]) def pushCharacter(self,char): self.myStack.append(char) def popCharacte...
5e7076a97f0834a376045aaf924e4c927a18f5c9
Mustafa017/python-programs-
/OOP/OOP2.py
359
3.671875
4
def make_account(): return {"balance":0} def deposit(account,amount): account['balance'] += amount return account['balance'] def withdraw(account,amount): account['balance'] -= amount return account['balance'] a = make_account() b = make_account() print(deposit(a,100)) print(deposit(b,200)) print...
2424c4700b765d208507bcb68197d30c7e8c9ca3
Mustafa017/python-programs-
/lists.py
7,223
3.90625
4
# -*- coding: utf-8 -*- """ Created on Tue Feb 7 12:57:05 2017 @author: mustafa """ list1 = ["a","b","c","d","e"] list2 = ["m","n","o","p","q","m"] list3 = ["h","i","j","k","l"] list4 = [1,2,3,4,5] list5 = [8,5,3,6,7,9] #lists are mutable(can be changed) (by adding elements to the list, it is changed) and elements ...
d31589125e4fa5ef611e2f59be04879122b3adf0
Mustafa017/python-programs-
/mod and divmod.py
252
3.90625
4
# -*- coding: utf-8 -*- """ Created on Sun Feb 12 15:03:31 2017 @author: mustafa """ a = int(input('Enter First number\n').strip()) b = int(input('Enter second number\n').strip()) print(a//b) #integral division print(a%b) #modulo print(divmod(a,b))
de6a499a1a4f3722ad410b08dd85449b585c25c3
Mustafa017/python-programs-
/array.py
447
3.6875
4
# -*- coding: utf-8 -*- """ Created on Sat Mar 11 12:30:30 2017 @author: mustafa """ #output is a reversed comma separated list n = int(input().strip()) arr = [int(arr_temp) for arr_temp in input().strip().split(' ')] print (arr[::-1]) #output is reversed space separated integers for i in range(n//2): temp = arr[...
0ae711119dcbe766541725a95a3fbd78649bebed
yujisatojr/py-algo
/data structures/stack/stack.py
1,701
4
4
class Stack: def __init__(self): self.head = None self.size = 0 def push(self, d): newNode = Node(d) if (self.head == None): self.head = newNode else: current = self.head while (current.next != None): current = current....
e5fe0938e0b8b0550200490917fd5ddc89f4fbf9
Sutanshu/MacOS-Automatic-DesktopWallpapers
/src/api/weather.py
822
3.609375
4
import requests from api.apiKey import API_KEY from api.coordinates import coordinates import json def getWeather(): content = '' try: if len(coordinates) == 2: result = requests.get("http://api.openweathermap.org/data/2.5/weather?lat={}&lon={}&units='metric'&appid={}".format(coordinates[0]...
85adfa2ba87d0ca94cefa4483d972f899cd1017e
Francis-Bui/ICS3U1
/CompactVowelSearcher.py
967
3.90625
4
# Constants vowelCount = 0 vowelPass = 0 # Variables letter = "a" string = str(input("What's the sentence?")) # Run code block five times while vowelPass < 5: for x in string: if vowelPass == 0: if (x == "a"): vowelCount += 1 letter = "a" ...
b9e35dadb2bf09b0cbf3746c1577427df48aea70
RandomForestGump/CSE_4535_Fall_2021
/project2/linkedlist.py
4,230
3.953125
4
''' @author: Sougata Saha Institute: University at Buffalo ''' import math class Node: def __init__(self, value=None, next=None, tf = 0, tf_idf = None): """ Class to define the structure of each node in a linked list (postings list). Value: document id, Next: Pointer to the next node ...
83244684b3c09d0bdf470b42dd947222b1c9d42a
true2000/Python-Project-1
/Python Project 1.py
774
4.40625
4
# This tool is used to help with the calculation of how much a hotel cots # Your Name # Aug 28 2020 name = input("What is your customers name?: ") def main(): print("\n") print("Hello " + name + " welcome to the Owl Hotel") print("This program allows you to calculate the total cost of a hotel.") pri...
29ecb9fce390093612cbc6fe741e9f994b31a7cb
jerry82/PyCrackCode
/Chapter9_SortSearch.py
9,077
3.625
4
class Chapter9: #O(n^2) def bubbleSort(self, arr=[]): tmpArr = arr[:] if (len(tmpArr) >= 2): l = len(tmpArr) for i in reversed(range(0,l)): for j in range(0, i): if (tmpArr[j] > tmpArr[j+1]): tmp = tmpArr[j] tmpArr[j] = tmpArr[j + 1] tmpArr[j + 1] = tmp self.printArr(tmpAr...
058f2c4a4b28430cc24965c66e3b8ef9a87f3436
Nandhinijsr/codekat
/guvi19.py
137
3.8125
4
Num=int(input()) sum=0 temp=Num while(temp>0): c=temp%10 sum+=c**3 temp//=10 if(Num==sum): print("yes") else : print("no")
9c2b8cf16ee45c35967b3fccd65fb915d92042e6
Nandhinijsr/codekat
/s44.py
74
3.65625
4
str=input() x=0 for j in str: if j ==".": x+=1 print(x+1)
96aad8061978f211c7ef24183ced2446d5e2bf70
Nandhinijsr/codekat
/s76.py
126
3.609375
4
p=int(input()) q=1 for j in range(2,p+1): if p%j==0: q=q+1 if q==2: print("yes") else: print("no")
eb08baa2b280a56743dc2f517dcc403b8aa24cbf
Nandhinijsr/codekat
/s610.py
55
3.609375
4
string1=int(input()) print((string1*(string1+1))//2)
80fc4ccce0ec8b4bbe10a43154cd27e1770ab82f
Nandhinijsr/codekat
/s52.py
90
3.59375
4
p,q=input().split() if p==q: print(p) elif(p>q): print(p) else: print(q)
9b9e56182ead7f27cb05b6de902ffe0046222186
Nandhinijsr/codekat
/s89.py
105
3.71875
4
p,q=input().split() p=int(p) q=int(q) x=p*q r=x**0.5 if r**2==x: print("yes") else: print("no")