blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
f227f9eeb846c6faf3f4b36e0b7d0930837adf59
sahaj2005/pythonLearning
/pythonlearning2.py
379
4.25
4
#string str1='hello world' str2="this is good boy " print(str1) print(str2) #index my_str="My name is jhon" print(my_str[0]) print(my_str[-1]) print(my_str[1:5]) print(len(my_str)) print(my_str.lower()) print(my_str.upper()) #replace str2="My name is saju" print(str2.replace('s','S')) print(str2.count('a')) str3="...
719d9d0e1b3548a2b791779d09693228e0824ab7
prof-paradox/project-euler
/7.py
520
4.125
4
''' Calculates the 10001st prime number ''' import math def isPrime(num): if num % 2 == 0: return False for i in range(3, round(math.sqrt(num)) + 1, 2): if num % i == 0: return False return True natural_no = 3 prime_count = 1 # initial count for 2 max_prime = 2...
ab4c0e1e97515eb083e35964b96d7f9ba5d62c01
prof-paradox/project-euler
/56.py
251
3.796875
4
''' Calculates the maximum digit sum of a^b where a, b < 100 ''' sum = None max_sum = 0 for i in range(91, 100): sum = 0 for num in str(99 ** i): sum += int(num) if sum > max_sum: max_sum = sum print(max_sum)
d3d288d75c7666fe4b41d36f677b347d8bfd85ea
JhonBv/MOPCalculatorAPI
/src/Plugins/MOP.Calculator.Python/MOP.Calculator.Python.py
1,248
4.0625
4
class Calculator: def __init__(self, operation, number1, number2): self.operation = operation self.fvalue = number1 self.svalue = number2 def doCalculate(self, operation, fvalue, svalue): while True: if self.operation in ('1','2','3','4'): ...
39c2be21cacb9d854add7c4babc773ca82f6951e
CloudsAndConcerts/scripts
/DataUtility/find_similar_queries.py
2,128
3.65625
4
#!/usr/bin/python # -*- coding:utf-8 -*- import csv, sys # python adaption of strike a match: https://gist.github.com/1063364/8b8970bb617c2f8689fedc50721e7bcc60767df8 def _get_character_pairs(text): if not hasattr(text, "upper"): raise ValueError("Invalid argument") results = dict() for word i...
a9e8d9aaaeea9975c5eddcbe70d0e91fe223b69b
rawsashimi1604/Qns_Leetcode
/leetcode_py/best-time-to-buy-stock.py
492
3.59375
4
from typing import List class Solution: def maxProfit(self, prices: List[int]) -> int: # Set profit to 0 prof = 0 buy = prices[0] for num in prices: # if current iteration is less than first, set current iteration to buyprice if num < buy: ...
db37990f15e0b9eaeab5dacf38b1adf87735b416
rawsashimi1604/Qns_Leetcode
/leetcode_py/valid-parentheses.py
834
4.125
4
class Solution: def isValid(self, s: str) -> bool: stack = [] lookup = { "}": "{", ")": "(", "]": "[" } for p in s: if p in lookup.values(): stack.append(p) # Must make sure that stack exists, so that there...
f844ab469d35a93ac945a2b0d0a6914518ffbe83
rawsashimi1604/Qns_Leetcode
/udemy_py_DS&A/stack_queue/43.py
772
3.640625
4
class MaxStack: def __init__(self): self.mainStack = [] self.maxStack = [] def push(self, data): self.mainStack.append(data) if len(self.mainStack) == 1: self.maxStack.append(data) return if data > self.maxStack[-1]: self.maxStack....
0458eb0803764b0957e65bfabcdeac6ab70fbe32
rawsashimi1604/Qns_Leetcode
/leetcode_py/length-of-last-word.py
505
3.625
4
class Solution: def lengthOfLastWord(self, s: str) -> int: if s == " ": return 0 list_of_words = s.split(" ") length = len(list_of_words[-1]) if length == 0: for i in range(1, len(s.split(" ")) + 1): if len(list_of_words[-i]) != 0: ...
3bb9535313b723ea50f3e86a1e6577a3c55372b5
rawsashimi1604/Qns_Leetcode
/leetcode_py/merge-sorted-array.py
424
3.859375
4
from typing import List class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ if len(nums2) != 0: mIdx = m for i in range(n): nums1[mIdx] = ...
56054096165677e2b086bce0197d1f520dfa8a56
yao1yao/python_effective_programm_skills
/some_training/set_select_value.py
127
3.59375
4
from random import randint data = [randint(-10,10) for _ in range(10)] s = set(data); print({x for x in s if x%3 == 0})
64c73e1428c91ca4c71ccb2d2ab2930451e4e222
yao1yao/python_effective_programm_skills
/file_io_processing/file_six.py
818
3.5
4
# -*- coding: utf-8 -*- # 如何使用临时文件 # 实际案例 # 某项目中,我们从传感器采集数据,每收集 # 到 1G 数据后,做数据分析 # 最终只保存分析结果,这样很大的临时数据 # 如果常驻内存,将消耗大量内存资源,我们可以使用临时 # 文件存储这些临时数据(外部存储) # 临时文件不用命名,且关闭后自动被删除 # 解决方案 # 使用标准库中 tempfile 下的 TemporaryFile,NamedTemporaryFile from tempfile import TemporaryFile,NamedTemporaryFile f = TemporaryFile() f.wri...
1158fc18d4183361d12609ea1f32afb9337ae100
yao1yao/python_effective_programm_skills
/some_training/list_select_value.py
445
3.8125
4
# 过滤列表中的负数 from random import randint import timeit; # 这里 _ 表示丢弃变量,和 for i in range(5) 没有区别 # 生成 -10 10 之间的10个数 # 后面生成的数值会被前面的替换 data = [randint(-10,10) for _ in range(10)] # 第一种过滤器 print(list(filter(lambda x: x>=0,data))); #print([item for item in data]); # 第二种 列表解析,会比过滤器更加快 print([x for x in data if x>=0])
095544f9d7130b903c9d28a8f3fe31261a5baaa0
yao1yao/python_effective_programm_skills
/some_training/keep_dict_sort.py
996
3.5
4
# 如何让字典保持有序 d = {} d['Jim']=(1,35) d['Leo']=(2,37) d['Bob']=(3,40) # python3 虽然会记录插入顺序,但是不建议使用 # for k in d: print(k) # output: # Jim # Leo # Bob # 使用 OrderDict from collections import OrderedDict b = OrderedDict(); b['Jim']=(1,35) b['Leo']=(2,37) b['Bob']=(3,40) for k in b: print(k) # 按排名顺序依次打印选手成绩 from time i...
e8204ea806d968c4561ff6a5ff40877a0bac3a05
TurboPikk/Prosjekt2
/Project 1 - Extended Edition.py
2,927
4.0625
4
from random import randint def main(): retard_level = 0 while play_game(retard_level) == True: retard_level += 1 print("Bye!") def generate_target(lowest, highest): target = randint(lowest, highest) return target def generate_guess(tries): guess_loop = True w...
ceb35d799bf4e0765f080f4d22e4eb4b883580eb
yana-davydenko/MyProject-list
/list2.py
187
4.03125
4
thislist = ['dress', 'skirt', 'shirt', 'shorts'] thislist.append('shoes') for x in thislist: print(x) thislist = ['dress', 'skirt', 'shirt', 'shorts'] thislist.pop() print(thislist)
4bef7953b5488328d2ff80b86c997185146b1f89
zeamic/Activity-2---Fibonacci-
/fib1.py
2,665
3.921875
4
# FINAL fib1.py !!!!! import time import matplotlib.pyplot as plt terms = [] run_time = [] print("Fibonacci using Recursion") n = 0 def recfibo1(n): if n <= 1: return n else: return(recfibo1(n-1) + recfibo1(n-2)) r1 = int(input("No. of terms: ")) terms.append(r1) start_time = time.time() if r...
2c9866a58c799fd92929b5be6a75655974430721
zouwensong/gitrsep
/第一次1.py
4,391
3.625
4
import re # 读取目标文件,以列表形式返回,去除符号 # 输入文件的相对路径,输出去除所有符号并以换行符分割文件内容的列表 def read_text(path):# path为传入的c,cpp路径 try: fp = open(path, 'r', encoding='utf-8') str_str = '~`!#$%^&*()_+-=|\';":/.,?><~·!@#¥%……&*()——+-=“:’;、。,?》《{}' file_text = re.sub(r"[%s]+" % str_str, " ", fp.read()) # 通过正则化原文本内容,去除所有...
01aae48727827602fbd3c2e05efbd5bdc9210cd0
zrx9718/graduation-project
/search.py
2,110
3.53125
4
dict = {'city': '', 'price': [], 'abovePrice': [], 'belowPrice': [], 'address': '', 'hotel': '', 'require': ''} def search(dict1): # 传入字典 city = dict1['city'] price = dict1['price'] abovePrice = dict1['abovePrice'] belowPrice = dict1['belowPrice'] ...
95c3f269511b3b9c0fd8722dd8a3c8ffb0c6849f
rockychen-dpaw/django-mvc
/django_mvc/forms/fields/coerces.py
437
3.515625
4
def coerce_TrueFalse(value): if value is None or value == '': return None if isinstance(value,str): return value == "True" return value def coerce_YesNo(value): if value is None or value == '': return None if isinstance(value,basestring): return value == "Yes" r...
9bd086c699ffc00aa1f0c3dc032a836f2013af87
JorgeMJ/border_analytics
/src/functions.py
3,031
3.671875
4
import csv import decimal import datetime def create_lists(): '''Returns two lists alphabetically sorted in reverse. One contains the types of border. The other one contains the means of crossing the border.''' borders = set() transports = set() try: with open('./input/Border_Crossing...
4a07c787d0905473339a2c05ec463ab901affc71
fightTone/Machine-Problems
/python/lin_bin_search.py
1,693
3.625
4
import fileinput import time fname = raw_input("Enter file name: ") def bi_search(data,number): low = 0 up = len(data) while low < up: x = low + (up - low) // 2 val = data[x] if number == val: result = x+1 return result elif number > val: ...
508d5c022e086494faddbbe6817ddabfbe79337f
callumr1/Programming_1_Pracs
/Prac 4/lotteryticket_generator.py
570
4
4
def main(): number_of_tickets = int(input("How many quick picks? ")) generate_tickets(number_of_tickets) def generate_tickets(number_of_tickets): import random for x in range(1, number_of_tickets + 1): rangeMax = 45 rangeMin = 1 ticketMax = 7 ticket = [] for ...
c64a94d4fc1eca7f25fc05aebafd61f8661fed1a
callumr1/Programming_1_Pracs
/Prac 3/name_check.py
355
3.953125
4
def main(): import random def get_name(): name = str(input("Please enter your name: ")) if name == "": print("You didn't enter your name!") else: n = random.randint(1, len(name)) print_name(name,n) def print_name(name,n): print(name[::n]...
df38b1d404b01498a368916adb754a496f354c1e
callumr1/Programming_1_Pracs
/Prac 4/number_list.py
681
4.15625
4
def main(): numbers = [] print("Please input 5 numbers") for count in range(1, 6): num = int(input("Enter number {}: ".format(count))) numbers.append(num) average = calc_average(numbers) print_numbers(numbers, average) def calc_average(numbers): average = sum(numbers) / len(nu...
c543270a6ffa5c251551c3cc3eb2082e013a2e0e
CRUZEAAKASH/PyCharmProjects
/section3_StringsAndPrint/String Methods.py
1,469
4.5
4
""" len() and str() practice: 1.create a variable and assign it the string "Python" 2.create another variable and assign it the length of the string assigned to the variable in step 1 3.create a variable and use string slicing and len() to assign it the length of the slice "yth" from the string assigned to the variabl...
15d758afcd551443056c912accd5a639b0d150c2
CRUZEAAKASH/PyCharmProjects
/section4_ConditionalsAndFlowControl/BooleanOperatorProblems.py
1,605
4.625
5
""" and, or, and not: 1.create a variable and set it equal to True using a statement containing an "and" Boolean operator 2.create a variable and set it equal to False using a statement containing an "and" Boolean operator 3.create a variable and set it equal to True using a statement containing an "or" Boolean operato...
a613635ed6f715c4cf389b39b91c058f2802e4cf
CRUZEAAKASH/PyCharmProjects
/section16_DataAnalysis/SortingDataFrame.py
620
4.03125
4
from pandas import DataFrame data = {'Name': ['John', 'Tom', 'Rob'], 'Age': [10, 20, 30], 'Salary': [2500, 35000, 4500]} frame = DataFrame(data) frame = frame.reindex([2, 0, 1]) print(frame) # sorting on the basis of row in ascending order frame2 = frame.sort_index() print(frame2) # Sorting on the b...
748717191efd26383d98236d4528e2508e137212
CRUZEAAKASH/PyCharmProjects
/section14_RegularExpressions/StarMatachracter.py
102
3.671875
4
import re pattern = r"eggs(bacon)*" if re.match(pattern, "eggsbaconbacon"): print("Match found")
cafc90b922a9c73f77e2ff2d3020c8563e93d60b
CRUZEAAKASH/PyCharmProjects
/section14_RegularExpressions/findAll.py
215
4.15625
4
import re pattern = r"eggs" String = "We have eggs in our string. eggs just eggstoeggs count the presence of eggs in the string" print(re.findall(pattern, String)) print(re.findall(pattern, String).__len__())
f5b2f41977280c6920d18c3736071647b38f0786
CRUZEAAKASH/PyCharmProjects
/section5_Functions/FunctionsProblems.py
2,525
4.875
5
""" Single parameter and zero parameter functions: 1.define a function that takes no parameters and prints a string 2.create a variable and assign it the value 5 3.create a function that takes a single parameter and prints it 4.call the function you created in step 1 5.call the function you created in step 3 with the v...
e15f7bfe9996364a015cbc4b10ae6d7b1a1f0270
CRUZEAAKASH/PyCharmProjects
/section5_Functions/ImportingModulesProblems.py
717
4
4
""" Importing Modules: 1.Use a generic import to import the "random" module 2.Use a universal import to get everything from the "math" module 3.Use a function import to get the exit() function from the "sys" module 4.Use a function from the random module to generate a float greater than or equal to 0 and less than 100 ...
1a07035dcb4f3909b26f5b0aa1d1b4af20192866
CRUZEAAKASH/PyCharmProjects
/section15_Tkinter/TkinterMessageBox.py
340
4.125
4
from tkinter import Tk from tkinter import messagebox window = Tk() messagebox.showinfo("title", "You are seeing message box") response = messagebox.askquestion("Question 1", "Do you love Coffee?") if (response == 'yes'): print("Here are your coffee loverrr!!!!!!!!!!!!!!!!!") else: print("What do you love???"...
85937ef07b71ea89a421ae26d6c601045e75fac8
CRUZEAAKASH/PyCharmProjects
/section15_Tkinter/LearningFrame.py
327
3.6875
4
from tkinter import * window = Tk() window.title("GUIIIIIIIIIIIIIII") frame1 = Frame(window) frame1.pack() frame2 = Frame(window) frame2.pack(side=BOTTOM) button1 = Button(frame1, text = "Click Here", fg = "Red") button2 = Button(frame2, text = "Click Here", fg = "Blue") button1.pack() button2.pack() window.mai...
3f27670d62a4383fd93019e0b0a859b9897b96a1
CRUZEAAKASH/PyCharmProjects
/section3_StringsAndPrint/StirngFormatting.py
296
3.90625
4
city = "Seatle" state = "Washington" print("The seahwaks are from %s, %s"%(city,state)) numbers = [4,5,6] print("Numbers are written in string format %s,%s,%s"%(numbers[0],numbers[1],numbers[2])) print("Numbers are written in string format {0},{1},{2}".format(numbers[0],numbers[1],numbers[2]))
761ff7f63f3fdf5b9d24f8f03835ca13554c323f
MiguelDotL/Udemy-Python
/oop_python/classes.py
3,693
3.609375
4
class Employee(object): raise_percent = 1.04 employee_count = 0 def __init__(self, first_name, last_name, salary, company='company'): self.first_name = first_name self.last_name = last_name self.email = str(first_name + '.' + last_name + '@' + company + '.com').lower() self...
8ff815a224a3b28ec0003892f91a306ee6c9c399
callumgoodley/python
/Code/cotd_1.py
453
4.03125
4
# CHALLENGE OF THE DAY: Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 (both included). The numbers obtained should be returned in a comma-separated sequence on a single line. def seven_not_five(): multiples = [] for i in range(2...
0a639c046972ff6f27897c6664efa1a3dcb998f5
procyon-cm/free-code-course
/arithmetic_arranger.py
2,500
3.90625
4
def arithmetic_arranger(problems, *args): EMPTY_SPACE = ' ' lst_1_line = list() # final lists lst_2_line = list() lst_dashes = list() lst_result = list() for problem in problems: num_and_oper = problem.split() ...
bc1b22c4c54e0beccf0c19de1103c3f7b5420380
rozuur/peuler
/problem57_continuedfract.py
706
3.59375
4
""" Non brute solution is related to finding patterns of terms for whicn num>den continued fraction of two is in form 1 + 1/2 = 3/2 = 1.5 1 + 1/(2 + 1/2) = 7/5 = 1.4 1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666... 1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379... 1 + 1/ 1 + 1 1 + 1/(1 + 3/2) 1 + 1/(1 + 7/5) 1+1/(1+a...
ef26690eccdd553f9a81cd1b9daa6f5c9e02cb93
chithracmenon/AutomateBoringStuff
/ch7_date_detection.py
1,743
4.71875
5
"""Date Detection Write a regular expression that can detect dates in the DD/MM/YYYY format. Assume that the days range from 01 to 31, the months range from 01 to 12, and the years range from 1000 to 2999. Note that if the day or month is a single digit, it’ll have a leading zero. The regular expression doesn’t have t...
4789752bb51887c082a5bb3d58df319065757c40
samirr14/bullet
/main.py
6,904
3.5625
4
""" Main file Name Bullet VS Description: 2 player arcade game 2D interface Each player on one side of the screen shooting bullets one to another until one dies. """ import arcade import random #Import Classes from static import Wall from players import P1, P2 from flying import Bullet1, Bomb from power ...
75d42f8678e39cd8f83ae6962467f2e297767285
lang98/conga-game
/player.py
3,536
3.890625
4
from abc import abstractmethod, ABC from typing import List, Tuple, Optional from board import Board class Player(ABC): def __init__(self, c: str): self.player_color = c self.opponent_color = 'B' if c == 'W' else 'W' self.moves = [ (1, 0), (-1, 0), (0, -1), (0, 1), ...
f2e7b1b9849a199b1d08a931191ef601c3409b6d
kouroshHakha/efficient_ga
/src/bagnet/util/iterators.py
975
3.703125
4
import random class BatchIndexIterator: """A class for iterating through indices of a dataset to produce a batch via slicing""" def __init__(self, data_set_size, batch_size): self._data_size = data_set_size self._batch_size = batch_size self._segment = self._data_size // batch_size ...
0317ab5f4681a628fa5aa26bdc8436f7a3a0a420
drodriguez32/Introduction-to-Python
/Section_8-Loops/Pig_Latin_Translator.py
902
3.96875
4
# get sentence from user original = input("Please write the sentence you want to translate: ").strip().lower() # split sentence into words words = original.split() # loop through words and convert to Pig Latin new_words = [] for w in words: # if it starts with a vowel just add "yay" to the end if w[...
82721669ddfcfe45621cb61b81a6f661d722e15e
JaneNjeri/python_crash_course
/elec_car.py
1,290
4.0625
4
"""Set of classes to rep elec cars""" from car import Car class Battery(): """Simple attempt to model a bettery for an electric car.""" def __init__(self, battery_size=70): """Initialize the battery's attributes.""" self.battery_size = battery_size def describe_battery(self): """Print a statment describing ...
d7dad337a80c37d8ce0a20101258132a2d5a5324
JaneNjeri/python_crash_course
/chapter10/file_reader.py
527
3.5625
4
# The keyword with closes the file once access to it is no longer needed. # here is an example of a file path # example of absolute path # file_path = 'C:\Users\ehmatthes\other_files\text_files\filename.txt' # with open(file_path) as file_object: #with open('py_text_files/pi_digits.txt') as file_object: # contents =...
4a891d4030805ca7bab9a9b2538d3c2084cd3114
JaneNjeri/python_crash_course
/factorial.py
235
4.3125
4
def factorial(num): if num == 0: return 1 else: return num * factorial(num - 1) print("Please enter a number to recieve its factorial.") num = int(input() ) print (factorial(num)) # good recursion practice
cde34a198a2699acfbae74f87e49c60b43fb85bd
annisa-nur/wintersnowhite
/exception.py
2,550
4.1875
4
# Program ini meminta pengguna memasukkan dua angka untuk operasi pembagian # Program menampilkan pesan jika terjadi eksepsi def main(): # [1] Tuliskan statement try/except # Pada body klausa try: # - Minta dua angka ke pengguna # - Lakukan pembagian # Pada body klausa except untuk Va...
da211a279fca121ab5531e59190dc9d0c4198a5c
annisa-nur/wintersnowhite
/processingrecord.py
1,698
4.25
4
# Program ini menambahkan record nilai mahasiswa # ke file nilai_mahasiswa.txt def main(): # [1] Minta pengguna berapa banyak record yang ingin dimasukkan jmlRec = int(input("Berapa banyak record nilai mahasiswa yang ingin Anda tambahkan? ")) # [2] Buka file dengan statement with, minta input mas...
c4d4a89aaecaed18084dbfe30d32b743ca736ace
x98426614/280201080
/lab7/example7.py
547
3.734375
4
list1 = [("Jon",15), ("Ned",45), ("Arya",9), ("Catelyn",44), ("Bran",10)] for a, b in list1: if b > 18: print(a) #New example books = ["ULYSSES","ANIMAL FARM","BRAVE NEW WORLD","ENDER'S GAME"] book_dict = {} for i in books: key = i value1 = len(i) value2 = len(set(i)) value3 = (value1+value2)/2 book_...
f5a59324054deda0abf09e314c4c404b958e5992
KushalNS/hello-world
/Vote.py
126
4.125
4
age=int(input("enter your age":)) if age>=18: print("your eligible to vote") else: print("your not eligible to vote")
749b9c615bf22938cbce0d868082615f2e58f644
jquintero9/snake
/utils.py
574
4.0625
4
class Stack(object): """ This class simulates behavior a stack. """ def __init__(self): self.__items = [] def is_empty(self): return self.__items == [] def push(self, item): self.__items.append(item) def pop(self): if not self.is_empty(): self...
b8f0670de4e5daf17e1528745517b3b6642cd3bb
anshwhitehtjr/PRO-C104-MEAN-MEDIAN-MODEL
/Mean.py
497
3.71875
4
import csv from os import read # storing the value of the csv file to f with open("HW.csv", newline='') as f: reader = csv.reader(f) file_data = list(reader) file_data.pop(0) new_data = [] for i in range(len(file_data)): n_weight = file_data[i][2] new_data.append(float(n_weight)) nu...
738704c562d88c0a06bc8e2e69b46adf026d92d7
ss1350/EAU_Ex
/Ex05/Ex05.py
5,921
4.09375
4
#!/usr/bin/python3 # coding=<UTF-8> # <<< Start of code from math import sqrt from itertools import count, islice import random from random import randint def isPrime(n): """check for prime number """ if n < 2: return False for number in islice(count(2), int(sqrt(n)-1)): if not n%number: ...
ab5c0b7bfce4b4c70cc60bf35f346d921f41d4e8
ss1350/EAU_Ex
/Ex13/graph.py
12,864
3.65625
4
#!/usr/bin/python3 import re import heapq class Graph: def __init__(self): self._num_nodes = 0 self._num_arcs = 0 # List for storing node objects. self._nodes = [] # List of lists for storing edge objects for each node. self._adjacency_lists = [] def read_gra...
ac74ba0fde939786aca05fff2648c368f46db4ef
miaha15/Programming-coursework
/Week 5 Question 1.py
974
4.34375
4
''' Premade list is given to the function A for loop is used to step through the list As it steps through each value of the list, it appends the list called TempList If the current element is GREATER than the next element of the list then it will check if everything stored in the TempList upto current element is longer...
9828f9e8b9cbccd772bd07d4f8dbc6776d9aec17
bnsh/pyeuler
/prob7.py
361
3.609375
4
#! /usr/local/bin/python def sieve(n): isPrime = [] primes = [] i = 1 while (i <= n): isPrime.append(1) i = i+1 j = 2 while (j < n): while ((j < n) and (not isPrime[j])): j = j + 1 if (j < n): primes.append(j) k = 2 * j while (k < n): isPrime[k] = 0 k += j j = j + 1 return(primes) ...
537986c669bbe7eb0b11e17d2adca13263268c0e
bingo8670/learnPythonWithCarter
/38_random.py
179
3.5625
4
#! python2 import random print random.randint(0, 100) print random.randint(0, 100) print random.random() print random.random() print random.random()* 10 print random.random()* 10
6afb3662a5dce6ee1993e1a4fba470ff1ceaac55
bingo8670/learnPythonWithCarter
/13.2_longAddress.py
482
3.96875
4
#! python2 # define a function with seven arguments def printAddr(name, num, street, city, prov, pcode, country): print name print num, print street print city, if prov !="": print ", "+prov else: print "" print pcode print country print #call the function and pass s...
f5bc076a39fd7f1dc8f5e590d81313ce6f28581a
bingo8670/learnPythonWithCarter
/12.1_namelist.py
174
4.0625
4
#! python2 print "Enter 5 names:" names = [] for i in range (1, 6): name = raw_input() names.append(name) print "The names are ", for name in names: print name,
a29b23a26f1ed6ad50aad25dab1c55a844e3ced6
bingo8670/learnPythonWithCarter
/7.1_price.py
261
3.96875
4
#! python2 #-*- coding: UTF-8 -*- price = float(raw_input("What's the price of it?")) if price <= 10: total = 0.9 * price print "您的折扣是10%" else: total = 0.8 * price print "您的折扣是20%" print "您的最终价格是" print total
9067db5d36f43f7d225c98628272ab067ac8dbd9
yerol89/100_Days_Of_Coding_With_Python
/1. Day_1_Working With Variables to Manage Data/Day1.py
861
4.1875
4
print("Day 1 - String Manipulation") print("String Concatenation is done with the '+' sign.") print("New lines can be created with a backslash.") print("Hello" + " " + "Everyone") print("Hello Python\nHello 100 Days of Coding") print("Hello" + " " + input("What is your name?\n")) name = input("What is your name? ") pri...
5e5d664cba8f82e045f025a763a3825d5342b0dd
msausville/ToolBox-Pickling
/counter.py
2,030
4.40625
4
""" A program that stores and updates a counter using a Python pickle file""" from os.path import exists import sys from pickle import dump, load def update_counter(file_name, reset=False): """ Updates a counter stored in the file 'file_name' A new counter will be created and initialized to 1 if none exists...
1e3809e37e1e46494b10dc94a918ad4ba9527096
Silvuurleaf/Perspective---Prototype-8-28-17
/TableUI.py
2,055
3.5625
4
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import (QLineEdit, QPushButton, QVBoxLayout, QHBoxLayout, QWidget, QLabel,QMainWindow) from PyQt5.QtCore import Qt, pyqtSignal class TablePopup(QMainWindow): """ The purpose of TablePopup class is for when...
b4f0b6061c28c03076425ae6a62e7aa417657e0b
yshaikhygali/Techdegree---Python-Web-Development
/unit-2-files/remember.py
681
3.828125
4
import sys def rememberer(thing): #open file # by default open is just for reading # file = open('database.txt', 'a') with open('database.txt', 'a') as file: #write thing to file file.write(thing + "\n") #close file # file.close() - No need def show(): # open file...
bd63202053d318bfe9c7f31851eef85de59822d5
Kill-Nickson/sn_test_task
/auto_bot/database.py
1,173
3.546875
4
from os.path import exists import sqlite3 class Database: def __init__(self, path='./databases/bots.db'): self.db_path = path def _table_init(self): try: with sqlite3.connect(self.db_path) as conn: cursor = conn.cursor() cursor.execute(""" CREATE T...
43cca6a5c26d24d5f1cf7fd4cd3666897536af9c
whimsicallyson/choleskiDecomposition
/matrixMult.py
745
4.03125
4
def matrixMult(matrix1,matrix2): ''' Multiplies two matrices together without numpy. Matrices are formatted as lists of lists. ''' r1 = len(matrix1) c1 = len(matrix1[0]) r2 = len(matrix2) c2 = len(matrix2[0]) answerList = [] for i in range(r1): for j in range(c2): ...
6853d2cffd47dee07900ff649fc12bc6d142949b
maumneto/IntroductionComputerScience
/CodeClasses/ConditionalCodes/cod10.py
1,326
4
4
# Um programa para gerenciar os saques de um caixa eletrônico deve possuir algum mecanismo para # decidir o número de notas de cada valor que deve ser disponibilizado para o cliente que realizou o # saque. Um possível critério seria o da “distribuição ótima” no sentido de que as notas de menor valor # sejam distribuída...
737c4183d9b77db804165e51af24f8a051e31ec9
maumneto/IntroductionComputerScience
/CodeClasses/FunctionsCode/cod1.py
286
4.28125
4
# O módulo Math possui um conjunto de funções import math num1 = int(input('Digite um valor numérico: ')) res = math.sqrt(num1) # nesta linha o código principal irá parar para executar a função math no sistema de módulos do python! print(f'A raiz quadrada de {num1} é {res}')
afe136b161db7f01215dd1faf7b9706f4befa586
maumneto/IntroductionComputerScience
/CodeClasses/ConditionalCodes/cod11.py
124
3.796875
4
i = int(input('Digite sua idade: ')) if (i % 2 == 0): i = i + 10 else: i = i * 2 print('idade final = %d' % i)
3817ff527fad3e572fc4f24cf62302ba6ee2f635
maumneto/IntroductionComputerScience
/CodeClasses/LoopCodes/cod9.py
562
3.921875
4
# Faça um programa que mostre os primeiros 10 termos da sequência de Fibonacci: # 0-1-1-2-3-5-8-13-21-34-... a = 0 b = 1 termos = int(input('Digite o número de termos desejados: ')) if (termos <= 0): print('Entrada Invalida!') elif (termos == 1): print(f'Termo 1 -> {a}') elif (termos == 2): print(f'Termo...
58fc3f2c0ddf2f38e512400f9c175a97ea24f102
maumneto/IntroductionComputerScience
/CodeClasses/FunctionsCode/cod5.py
1,248
3.796875
4
# Faça um programa que preencha um vetor com 10 elementos numéricos inteiros. # Calcule e mostre: # • todos os números pares; # • a quantidade de números pares; # • todos os números ímpares; # • a quantidade de números ímpares. # 1 criando a função para peencher uma lista com 10 elementos numéricos def preenche_vetor...
b0f128c5153d6fda8a084b51ce9eb1dcb5e1a213
maumneto/IntroductionComputerScience
/CodeClasses/FunctionsCode/cod6.py
245
3.59375
4
def somar(a,b): return a + b def criar_cadastro(): name = input('Digite o seu nome: ') age = int(input('Digite sua idade: ')) return name, age nome, idade = criar_cadastro() print(f'Olá sr(a) {nome}. Você tem {idade} anos!')
4b2011ee272cdbf2b8b093786a392f0752a5a7cd
maumneto/IntroductionComputerScience
/CodeClasses/SequentialCodes/cod7.py
566
4.125
4
""" Escreva um programa que pede os seguintes dados: • Valor do salário de um funcionário • Aumento em porcentagem Depois mostre o valor do aumento e o salário com aumento arredondados para duas casas decimais """ # entrada de dados salario = float(input("Digite o salario: ")) aumento = float(input("Digite a porcentage...
550985fc10331f44d0ce79d42b8a50981d1d93c8
mishratarini/608-mod7
/Bonus.py
1,153
3.765625
4
# Enable matplotlib import matplotlib.pyplot as plt import pandas as pd from scipy import stats from sklearn.linear_model import LinearRegression import seaborn as sns # Predict a point in the future. sales = pd.read_csv('SalesOfShampoo.csv') from sklearn.model_selection import train_test_split X_train, X_te...
811b7aed876004f7c5fca3b686a612c78c0e498d
nareshavula6460/test-python
/PatternProgram_2.py
162
3.875
4
n = int(input("Enter the number:")) count = 1 for i in range(1,n+1): for j in range(1,4): print(count,end=" ") count = count + 1 print()
85666135316aab2d74915d4828f9452a3d5dfe52
anhquan075/CS114.L21-L22.KHCL
/Assignments/Week1/Week1.2/Equal_String.py
313
3.5625
4
q = int(input()) result = [] for k in range(n): s = input() t = input() flag = False for i in s: if flag == False: for j in t: if i == j: flag = True else: break if flag: result.append('YES') else: result.append('NO') for i in result: print(i)
ed2c61e796340d34af332c8b59e55f2ec1b0e991
intevol200/Kookmin-University
/컴퓨터프로그래밍2/ramdom.py
569
4
4
import random answer = random.randrange(100) chance = 5 print("up-down Game !") print("정답이 생성되었습니다.") while True: print("남은 기회 : " + str(chance)) if chance == 0: print("실패 ㅠㅠ") break guess = int(input("정답을 입력하세요 : ")) if guess > answer: print("Down !") ...
7a655e9c3a0dc79e4791e11a9103a07ce0826e84
aWildOtto/chestnut-tutorial
/Jersey.py
1,876
3.9375
4
num_dict = {'Jersey number': [], 'Rating': []} jersy = 0 rating = 0 for i in range(0, 5): jersey = int(input(f'Enter player {i+1}\'s jersey number:\n')) rating = int(input(f'Enter player {i+1}\'s rating:\n')) print() num_dict['Jersey number'].append(jersey) num_dict['Rating'].append(rating) print(...
fec707a47fcb59964fbc59fd2a3fb2239a852bf0
Este1le/nparam
/get_nparam_rnn.py
9,640
3.625
4
#!/usr/bin/python """ Calculate the number of model parameters for RNN models. """ import argparse import os from collections import OrderedDict def multiple_values(num_values, greater_or_equal, data_type=int): """ source: https://github.com/awslabs/sockeye/blob/master/s...
00e3322beb3c82c40abea0ce841cda57e0adae40
prandzio99/University-Classes
/Numerical-Algorithms-UniLabs/Newtons-Polynomial-Interpolation/bezkom.py
3,687
3.671875
4
from sys import exit def check_sorted(tab, op="l"): i = 0 if op == "le": while i < len(tab) - 1: if tab[i] > tab[i + 1]: return False i += 1 else: while i < len(tab) - 1: if tab[i] >= tab[i + 1]: return False ...
8b61772524f3cdb8d5e2064389575eabe6472f2a
robertschult/python-crash-course-code
/lists.py
1,372
3.671875
4
bicycles = ['trek', 'cannondle', 'huffy', 'shwinn'] print(bicycles[0]) print(bicycles[0].title()) print(bicycles[-1]) message = f"My first bicyle was a {bicycles[0].title()}." print(message) shrooms = ['psylocybin', 'azurnces', 'mexicana', 'boys from brazil'] message = f"I especially love {shrooms[2].title()} mushrooms...
d64436ef1ca5cc256891852c534d83fc71d587a6
tkoz0/problems-online-judge
/vol_109/p10924.py
506
3.65625
4
import sys def value(c): if c.islower(): return 1+ord(c)-ord('a') else: return 27+ord(c)-ord('A') def prime(n): if n == 1: return True # exception required for this problem if n < 2: return False if n < 4: return True if n % 2 == 0: return False d = 3 while d*d <= n: if n % d =...
7f9a21f4eb9b936ae2fa63ff9ce0b53cbe662d13
tkoz0/problems-online-judge
/vol_104/p10424.py
606
3.671875
4
def digital_root(n): # from wikipedia if n == 0: return 0 if n % 9 == 0: return 9 return n % 9 chars = ' abcdefghijklmnopqrstuvwxyz' while True: try: s1 = input() s2 = input() except EOFError: break s1 = s1.lower() s2 = s2.lower() s1val, s2val = 0, 0 for c in s1: ...
e420b1d702ec600f17aefc9324daef9241d4adce
tkoz0/problems-online-judge
/vol_119/p11988_time_limit.py
1,273
3.671875
4
# this code is incorrect, assumes the whole input file is a single test case # the problem actually has 1 test case per line import sys typed = sys.stdin.read() # '[' = home # ']' = end # use a doubly linked list of strings to avoid reconcatenation of long lengths class node: def __init__(self,value): ...
1666257cecb148c51cd14e4e0b823dda64bee241
tkoz0/problems-online-judge
/vol_122/p12250.py
335
3.796875
4
lang = { 'HELLO': 'ENGLISH', 'HOLA': 'SPANISH', 'HALLO': 'GERMAN', 'BONJOUR': 'FRENCH', 'CIAO': 'ITALIAN', 'ZDRAVSTVUJTE': 'RUSSIAN'} case = 0 while True: case += 1 S = input() if S == '#': break try: print('Case %d: %s' % (case,lang[S])) except KeyError: print('Case %d: UN...
8af5c57a726d74cdfcd70461973007c62b2381e6
tkoz0/problems-online-judge
/vol_004/p494.py
310
3.5625
4
import sys letters = set('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz') for line in sys.stdin: # replace all non letters with spaces for asci in range(33,127): if not (chr(asci) in letters): line = line.replace(chr(asci),' ') print(len(line.split())) # only contains letters now
e6453be0f1f289cb1548979c0d13794dfe5f90fc
tkoz0/problems-online-judge
/vol_103/p10344_time_limit.py
777
3.734375
4
def search2(nums,current,goal): # pick a next number and operation if len(nums) == 0: return current == goal for i in range(len(nums)): a = nums[i] nums2 = nums[:i]+nums[i+1:] if search2(nums2,current+a,goal): return True # try 3 operations if search2(nums2,current-a,goal): retu...
7b34cf8d36b984bbbabce2e8430bbcce5ed77685
tkoz0/problems-online-judge
/vol_004/p489.py
790
3.75
4
while True: round = int(input()) if round < 0: break solution = input() guesses = input() print('Round',round) covered = set(solution) # correct letters not guessed yet guessed = set() hangman = 0 game_done = False for guess in guesses: if guess in guessed: continue # no...
904d680386af6aac4db93d1869a042bc7ace4a11
Xuanong/1008-lab-1
/WordLadder.py
6,730
3.65625
4
__author__ = 'Cristal Ngo' from MyQueue import MyQueue from MyStack import MyStack dictionary = [] def readFromDictionary(fileName): global dictionary f = open(fileName, "r") for line in f: line = line.replace("\n", "", ) line = line.lower() dictionary.append(line) dictionary...
5ec674815b4e8031477a68545e6fd10506ec3822
Thomas-Gill-96/DP2-Sprint2
/DP2_Project/Database_Queries.py
6,357
3.546875
4
import mysql.connector def cursorReset(): mycursor = mydb.cursor() def printSales(): mycursor.execute ('SELECT * FROM Sales') records = mycursor.fetchall() if not records: print("The records are currently empty.") else: for row in records: print("ID: " + str(row[0])) ...
8e43d61777bce94b14b9fe3f635098771155e46d
fuckdinfar/project-hehehehhehe
/Input functions.py
1,648
4.0625
4
import numpy as np # the following functions are meant as helping functions for the main script taking user input and displaying headers. def header(headerString): print(""" ==================== {} ====================\n""".format(headerString)) def inputStr(prompt): while True: try: ...
80f66606d42e2ac922bb94cdd17e108a381360ff
alexpear/hobby
/earlystages/palindrome.py
220
3.625
4
def palindrome(lefthalf): rightwithoutcenter = lefthalf[-2::-1] return lefthalf + rightwithoutcenter print(palindrome('NOSIRAWAYAPA')) # >>> palindrome.palindrome('TORRENTRAPTOR ') # 'TORRENTRAPTOR ROTPARTNERROT'
e37d69a3cdc6af881791f3c1ceaa352a07b0f3a6
alexpear/hobby
/genregen/worldTree/worldTree.py
9,585
3.578125
4
#!/usr/bin/python ''' Skeleton for genregens / random generators To use: Put a copy of this file in the dir, next to the tables as txt files. The file describing the main format of your generated strings should be called output.txt and should contain at least one line something like '9 {adj} {noun}'. (Then ofc you wou...
f54e97db00819653f138b612bf7de5dbf2ecf506
riochuong/AlgorithmsReview
/Stanford_Alg/Course_2/Graphs/SCC.py
4,797
3.515625
4
class SCC (object): def __init__(self, input_file): self.graphs = self.__constructGraphFromInputFile(input_file) def __constructGraphFromInputFile(self, input_file): """ return ajacent array format """ file = open(input_file) graphs = {} for line in...
f9eda12e0a2ba0482335532dfed5c992aee51f05
Safintim/24
/test6.py
910
3.703125
4
import unittest import task6 as t import time class MyTestCase(unittest.TestCase): def factorial(self, n): if n == 0: return 1 return n * self.factorial(n-1) def test_summation(self): for i in range(10**4 + 1): s = t.summation(str(10**8), str(i)) se...
970ad77d254b6d34e0a0d23474d04b5bfcac2462
Safintim/24
/task11.py
1,436
3.703125
4
from random import shuffle, randint from collections import deque def hack(array, count=3): array_sort = sorted(array) while array != array_sort: start_index = randint(0, len(array) - count) part_array = array[start_index:start_index + count] max_part_array = max(part_array) f...
fa0a8af71e4e7b6f3617b071143f73c8e3e6511a
shubhambajpai1994/user_engagement-videoken
/source/data_clean/teest3.py
282
3.515625
4
import datetime def extract_week_number(raw_date): year = '2018'#raw_date[:4] month = '02'#raw_date[5:7] day = '01'#raw_date[8:] dt = datetime.date(int(year), int(month), int(day)) wk = dt.isocalendar()[1] print wk extract_week_number('2018 04 06')
b374c7ad1cada462ba31bb14dd80f15142da3e48
Akshata1992/ComputerVision_DeepLearning
/PokedexDetection/classify.py
1,627
3.5
4
#Uasage-- Classify the images using trained model #import all necessary packages from keras.preprocessing.image import img_to_array from keras.models import load_model import numpy as np import argparse import imutils, cv2, os, pickle #construct argument parser ap = argparse.ArgumentParser() ap.add_argument("-m", "--m...
92c1a775413c401ff393231651d44063fe687e2b
barclayiversen/algos
/python/duplicate_encode.py
646
3.8125
4
# This algo is supposed to return parens based on whether the character in the string appears more than once or not (I think) # I believe this came from codewars test_a = "din" test_b = "recede" from collections import OrderedDict def duplicate_encode(word): word = word.lower() letter_count = OrderedDict() ...