blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
869539bec2506f38b099f99b7ffc6e976817fd4d
AKuvardin/stepic_auto_tests_course1
/ATcourse/lesson2.2_step3.py
966
3.5
4
from selenium import webdriver import time import math from selenium.webdriver.support.select import Select def sum(x, y): return str(int(x) + int(y)) try: link = "http://suninjuly.github.io/selects1.html" browser = webdriver.Chrome() browser.get(link) # выдергивание чисел со страницы и их сумм...
ae6ab59186e8361e41daa0a938b0785c5cd1b887
antony-wan/spark
/preprocessing_pyspark.py
2,640
3.5
4
''' Lectures followed on Datacamp ''' #################################### ######### Data cleaning ############ #################################### ''' Exemples : -wrong data type -range for numerical values -representation of unknown/incomplete data -absence des valeurs -column naming conentions -regional datatimes V...
6ebf6eac1e4477e7a1751df1a207db0997542c20
agrif/pyquickcheck
/quickcheck/roundrobin.py
502
3.59375
4
"""Round-robin for iterators.""" import itertools __all__ = ['roundrobin'] def roundrobin(*iterables): "roundrobin('ABC', 'D', 'EF') --> A D E B F C" # Recipe credited to George Sakkis pending = len(iterables) nexts = itertools.cycle(iter(it).__next__ for it in iterables) while pending: t...
71eba9f2a4be16b72b8b693731b36ba8ad22ac64
lechfras/CodeBrainer_1405
/DuzyLotek.py
740
3.609375
4
import random ileliczb=int(input("Podaj ilosc typowanych liczb: ")) maksliczba=int(input("Podaj maksymalna losowawna liczbe: ")) #print("Wytypuj %s z %s liczb: " % (ileliczb, maksliczba)) liczby=[] i=0 while (i < ileliczb): liczba=random.randint(1,maksliczba) if liczby.count(liczba)==0: liczby.append...
dd983b31721ab91cf0b98d496fadc6b434143309
Diwakar1988/python-samples
/Conditionals.py
940
4.09375
4
''' REMEMBER?? 1. if-else block scope is determined by indentation/alignment not by '{}' (parenthisis) 2. condition results should be either 'True' or 'False' constants 3. Any numeric value (positive/nigative), will be considered as 'True' condition ''' num = 10 color= "red" print("num=",num," color=",color) #SIMPLE...
48fd1c361a0cc49df05d63022117864f8795f03b
Diwakar1988/python-samples
/VariablesAndDataTypes.py
806
4.21875
4
#DECLARE A VARIABLE print("#DECLARE A VARIABLE") num = 10 floatNum = 10.5 strName = "Diwakar Mishra" listWeekDays=["S","M","T","W","T","F","S",7] dictinaryMonthDays = {"Jan":31,"Feb":28,"Mar":31,"Apr":30,"May":31,"Jun":30,"Jul":31,"Aug":31,"Sep":30,"Oct":31,"Nov":30,"Dec":30} print(type(num),num) print(type(floatNum),...
8e18a47aa95e213c277892662d3767b428e81c15
YangChenye/LeetCodeProblems
/2_Add_Two_Numbers.py
915
3.796875
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ def toStr(node): ...
417e85a1f9a6ef72ce254836d5c0cc5471b740e3
cyrilnigg/recursive-functions
/recursive.py
1,135
4.09375
4
#Various recursive functions def factorial(n): ''' Takes an integer greater than 0 Returns factorial value recursively ''' if n == 0: return 1 else: return n * factorial(n-1) def fib(n): ''' Takes an integer greater than 0 Returns Fibonacci value ''' assert type(n) == int and n >= 0 if n == 0 or ...
b901c18572ff54ffa21bc568493449aa5b616b30
Supreethamg/melon-delivery-report
/produce_summary.py
783
3.890625
4
def produce_summary(day_no, file_name): ''' Prints summary report when day number and path to the file is passed in parameter of the function.''' print("Day ", day_no) #opens the file the_file = open(file_name) #Generates report by reading line by line. for line in the_file: line = ...
4e6d6d5e22041ce8718fe6e720ac8b1d6795e432
pepelepew71/particle-filter-demo
/robot.py
2,711
3.640625
4
# from math import * import math import random from config import * import utilities class Robot: def __init__(self): self.x = random.random()*WORLD_SIZE self.y = random.random()*WORLD_SIZE self.orientation = random.random()*2.0*math.pi self.noise_forward = 0.0 # sigma s...
a3f2e3f76c5676aef36bcd84c6972ccef89b3589
NageshChendake/BankAtm
/foo.py
5,522
3.53125
4
''' pygamegame.py FRAMEWORK CREATED BY: Lukas Peraza ''' import pygame, webbrowser, os class PygameGame(object): def init(self): print(pygame.image.get_extended()) self.background = pygame.image.load("capitalOne.png") self.title = "Tartan Hacks" #TITLE self.names = "M...
d1f4dd716347cccdf9360c4cc2e8738bb6d0fb2e
adhi-r/ridesharing-model
/UberModel.py
13,571
3.890625
4
import matplotlib.pyplot as plt #%matplotlib inline import random import numpy as np from IPython.display import display, clear_output import time import math class driver(): """Creates a driver capable of picking up riders and taking them to their destination. Drivers may only have 1 rider at a time. """ ...
5e636c02ee4cf5bc580fd4804feeda2928c685f6
apookash55/PESU-IO-SUMMER
/coding_assignment_module1/ques3.py
607
4.0625
4
def binarySearch (arr, l, r, x): if r >= l: mid = l + (r - l)//2 if arr[mid] == x: return mid elif arr[mid] > x: return binarySearch(arr, l, mid-1, x) else: return binarySearch(arr, mid + 1, r, x) else: return -1 s=input("Ente...
015c1480d48f5d4e21bb845afd2b6c70f4d5eb6d
MasahiroKitazoe/leetcode
/easy-collection/LinkedList/reverse-linked-list/solution.py
645
3.78125
4
# https://leetcode.com/problems/reverse-linked-list/ # runtime beats 95.66% # memory usage beats 31.82% # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: i...
ba4abb07f5a01374047a4f0c0fabbb4b3cbaeb2f
rochejohn/ATBS
/Projects/Regex_strip.py
3,679
4.65625
5
#! /usr/bin/env python3 ''' Write a function that takes a string and does the same thing as the strip() string method. If no other arguments are passed other than the string to strip, then whitespace characters will be removed from the beginning and end of the string. Otherwise, the characters specified in the second...
463996ca7b86fd8b361b10b85074b2fbff150625
rochejohn/ATBS
/Projects/Spreadsheet_Cell_Inverter.py
1,469
4.375
4
#! /usr/bin/env python3 ''' Write a program to invert the row and column of the cells in the spreadsheet. For example, the value at row 5, column 3 will be at row 3, column 5 (and vice versa). This should be done for all cells in the spreadsheet. You can write this program by using nested for loops to read in the sp...
881a016777363ac140c677f886449044c7fe44fb
rochejohn/ATBS
/Projects/Debugging_Coin_Toss.py
1,150
4.25
4
#! /usr/bin/env python3 ''' The following program is meant to be a simple coin toss guessing game. The player gets two guesses (it’s an easy game). However, the program has several bugs in it. Run through the program a few times to find the bugs that keep the program from working correctly. ''' import random,logging...
97f39d320c957cd7ac74d7359cdce9fb0d02d593
User-11234/Hoque_Story
/Basics/evenOrOdd.py
208
4.25
4
num = float (input ("Please enter a number: ")) if (num%2)==int("1"): print("You have an odd number.") if (num%2)==int("0"): print("You have an even number.") else: print("This is not a number.")
03cd26d2d30a49a283ac836d038188cb2918a267
Johanawan/Algorithms
/DataStructuresAlgoInPython-Book/chap01/solutions/35.py
1,024
4.1875
4
# The birthday paradox says that the probability that two people in a room # will have the same birthday is more than half, provided n, the number of # people in the room, is more than 23. This property is not really a paradox, # but many people find it surprising. Design a Python program that can test # this paradox b...
bc332b25996815f0b447fc09dd75e39ecbb880c4
Johanawan/Algorithms
/DataStructuresAlgoInPython-Book/chap01/solutions/30.py
361
3.9375
4
# Write a Python program that can take a positive integer greater than 2 as # input and write out the number of times one must repeatedly divide this # number by 2 before getting a value less than 2. def n2times(x): count = 0 while x >=2: x = x/2 count += 1 if x<2: return st...
a817a916b74cd0484ce69ec3684cec8c0cfa051b
Johanawan/Algorithms
/DataStructuresAlgoInPython-Book/chap01/solutions/02.py
721
4.3125
4
# Write a short Python function, is even(k), that takes an integer value and # returns True if k is even, and False otherwise. However, your function # cannot use the multiplication, modulo, or division operators. def is_even(k): if k <= 0: return -1 else: # Method 1: Using modulus # if...
2bc4d92dda27dc4c10f802627c5324282c749b3b
Johanawan/Algorithms
/DataStructuresAlgoInPython-Book/chap01/solutions/29.py
235
3.671875
4
# Write a Python program that outputs all possible strings formed by using # the characters c , a , t , d , o , and g exactly once. from itertools import permutations perms = ["".join(p) for p in permutations("catdog")] print(perms)
863c278071aac50df02fb502edf15370f16f1aa9
liviagranato/trabalho-compiladores
/Analisador/src/analisador/codigo.py
482
3.890625
4
def testaPrimo(n): i = 1 numDivisores = 0 while(i <= n): if (n % i == 0): numDivisores = numDivisores + 1 i = i + 1 if (numDivisores == 2): return "Seu número é primo" else: return "Seu número não é primo" ...
9391b4b84dae4c7fa05309cc6245bc881f6a7880
elmtree-Ahn/python_algorithm
/codeup_basic100/no_78.py
115
3.578125
4
while True: data = input() if data == 'q': print(data) break else: print(data)
c55db7946eb9629e235d76a65802052dc4a1d493
elmtree-Ahn/python_algorithm
/beakjoon_step/4344.py
301
3.53125
4
import sys n = int(sys.stdin.readline()) for i in range(n): scores = list(map(int, input().split())) avg = (sum(scores) - scores[0]) / scores[0] count = 0 for j in scores[1:]: if j > avg: count += 1 result = count / scores[0] * 100 print(f"{result:.3f}%")
5cc00ab0d28a977836e33945e4279a15d5d164ed
elmtree-Ahn/python_algorithm
/codeup_basic100/no_27.py
53
3.578125
4
num = input() num = int(num) print(format(num, 'x'))
2d1cfdcca42837a8d0514635e8be2a00b3d6554c
tmsteen/training
/python-IV/lab_json.py
2,381
3.71875
4
#!/usr/bin/env python3 # *-* coding:utf-8 *-* """ :mod:`lab_json` -- JSON Navigation ========================================= LAB_JSON Learning Objective: Learn to navigate a JSON file and convert to a python object. Practice file IO using with. :: a. Using urllib2, explore the GitHub...
8bf208f66541668c8d46cb705591b5c9be2e8444
tmsteen/training
/python-IV/lab_flask.py
1,495
4.03125
4
#!/usr/bin/env python3 # *-* coding:utf-8 *-* """ :mod:`lab_flask` -- serving up REST ========================================= LAB_FLASK Learning Objective: Learn to serve RESTful APIs using the Flask library :: a. Using Flask create a simple server that serves the following string for the root route ('/'): "<h...
55ebbfc9da8d018b5e923200c072b5ade81be026
tmsteen/training
/python-IV/lab_yaml.py
3,637
3.8125
4
#!/usr/bin/env python3 # *-* coding:utf-8 *-* """ :mod:`lab_yaml` -- YAML Parsing ========================================= LAB_YAML Learning Objective: Learn to parse a YAML file using the PyYAML library and use the information. :: a. Start with your code (or the solution code) from l...
f3ca63ce492fc7de92781e8929e728549eb1fd52
Joe2357/Baekjoon
/Python/Code/2800/2839 - 설탕 배달.py
168
3.5
4
n = int(input()) boolean = True for i in range(n//5, -1, -1): if(not((n - i * 5) % 3)): print(i + (n - i * 5) // 3) boolean = False break if(boolean): print(-1)
dbdc0f29bd7a6c8f1f9a80e871e9abb447857568
Joe2357/Baekjoon
/Python/Code/2900/2908 - 상수.py
209
3.65625
4
a, b = input().split() for i in range(2, -1, -1): if a[i] > b[i]: for j in range(2, -1, -1): print(a[j], end = "") break elif a[i] < b[i]: for j in range(2, -1, -1): print(b[j], end = "") break
3cbe161a52c848a537d3fe23f5336da2190417cf
venksubbu/venkat
/evenorodd.py
141
4
4
#stylishsubbu77@gmail.com a=int(input()) if (a>0): if (a%2)==0: print('Even') elif (a%2)!=0: print('Odd') else : print('Invalid')
34c43bacaded7396fce65e1e8cd32e492f1a8bc7
Gabicolombo/Python-exercicios
/Dictionaries/exercício 4.py
384
3.84375
4
''' Given the dictionary swimmers, add an additional key-value pair to the dictionary with "Phelps" as the key and the integer 23 as the value. Do not rewrite the entire dictionary. ''' swimmers = {'Manuel':4, 'Lochte':12, 'Adrian':7, 'Ledecky':5, 'Dirado':4} swimmers['Phelps'] = 23 print(swimmers) # {'Manuel': 4, 'Loc...
54905e6dbe5de177d2fbb321da19e219661c7a3f
Gabicolombo/Python-exercicios
/Map, filter, list comprehensions/Filter.py
1,412
4.15625
4
def keep_evens(nums): new_seq = filter(lambda num: num % 2 == 0, nums) return list(new_seq) print(keep_evens([3, 4, 6, 7, 0, 1])) # Saída [4, 6, 0] ''' 1. Write code to assign to the variable filter_testing all the elements in lst_check that have a w in them using filter. ''' lst_check = ['plums', 'watermelon...
4bb676489b595611fadcf25317ebadd38145f38c
MahmoudAbbouchi/python_sql_test
/SQL_SampleCode.py
2,496
3.671875
4
#This is a python test code to attept to host/initialize an sql database #Sample code for the IEEE CSRC Software Fundementals SQL and Database #Change at will #Author: Mahmoud Abbouchi import sqlite3 sqlconnection = sqlite3.connect("company.db") #Create and connect to company.db cursor = sqlconnection.cursor() ...
90998230863cf859577bfac48f27506edcf9f2de
oliversalsjo/oliver-salsjoo-kursolle
/upgA.py
397
3.6875
4
#Gör skriv fält kunden s1 =int(input("ange sida 1: ")) s2 =int(input("ange sida 2: ")) #Multiplicerar båda sidorna och får därmed ut arean area = s1 * s2 print (area) #Jag skapade en if sats för att kontrollera om sida 1 = sida 2 och ifall dom är samma så skrivs kvadrat ut if s1 == s2: print ("kvadrat") else: ...
d95b9f7a668ae61372f2b3ae5cfe0e55436e1fe7
rogers228/Learn_python
/note/basic/03_判斷式與迴圈/test_if_01.py
109
3.953125
4
#a = True a = False if a is True: print('a is True:', a) else: print('a is False:', a)
3c2b241a9f6c1ed592143f04ba4cb2a6c6c05119
rogers228/Learn_python
/note/basic/08_時間/time_06_月份天數.py
540
3.8125
4
from datetime import datetime from datetime import timedelta def getYMdays(year_s, month_s): try: mydate = datetime(int(year_s), int(month_s), 1) old_Month = mydate.month new_Month = mydate.month i = 0 while new_Month == old_Month: mydate = mydate + timedelta(day...
dd20f5520da8bea13fadf8b77ab6a954996239f4
rogers228/Learn_python
/note/module/03_tkinter_圖形視窗介面/2018/tkinter03_窗體大小居中.py
697
3.5625
4
import tkinter as tk def get_screen_size(window): return window.winfo_screenwidth(),window.winfo_screenheight() def get_window_size(window): return window.winfo_reqwidth(),window.winfo_reqheight() def center_window(root, width, height): screenwidth = root.winfo_screenwid...
25ee485081cb54a800a1d05df2548dd8e0ac800a
rogers228/Learn_python
/note/basic/04_串列結構/list_12_最大最小索引.py
168
3.6875
4
mlis = ['a','b','c','d','e','f','g','h'] a, b = max(mlis), min(mlis) #最大索引的值 print(a) print(b) print(mlis[0]) #最小索引 print(mlis[-1]) #最大索引
cdfcb17c5f4c7095b95beafc4e64864a46c492d4
rogers228/Learn_python
/note/module/03_tkinter_圖形視窗介面/2018/tkinter17_popmenu.py
1,800
3.53125
4
import tkinter as tk def get_screen_size(window): return window.winfo_screenwidth(),window.winfo_screenheight() def get_window_size(window): return window.winfo_reqwidth(),window.winfo_reqheight() def center_window(root, width, height): screenwidth = root.winfo_screenwid...
f9b1f6df570df4d99f8372a557e42166932f2326
rogers228/Learn_python
/note/module/03_tkinter_圖形視窗介面/test/test1.py
1,327
3.546875
4
import tkinter import time Window_Width=800 Window_Height=600 Ball_Start_XPosition = 50 Ball_Start_YPosition = 50 Ball_Radius = 30 Ball_min_movement = 5 Refresh_Sec = 0.01 def create_animation_window(): Window = tkinter.Tk() Window.title("Python Guides") Window.geometry(f'{Window_Width}x{Window_Heigh...
101cd17e82539338ec81739fd479a0598c45e1b6
rogers228/Learn_python
/note/module/07_pandas_資料結構/test_依欄位值排序.py
418
3.796875
4
df.sort_values(by=['col1']) #單一欄位排序 df.sort_values(by=['col1', 'col2']) #多欄位排序 df.sort_values(by='col1', ascending=False) #反向 #含有不同型,將別無法排序 df['col1'] = df['col1'].apply(str) #將該欄位強制轉換為文字 #空白排在最前 #函數計算後排序 # 其他請參閱 https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html
a4329905ec15cf2971a29b61246e4233380819e6
rogers228/Learn_python
/note/basic/01_引用/test_import_02.py
294
3.5625
4
'''僅引用test_function_say模組裡的say程序 往後的程式碼不可再冠上模組名''' from test_function_say import say say('hello',3) #test_function_say.say('hello',3) #錯誤,不可在冠上模組名稱 #say2('hello') #錯誤,未引用say2程序,無法使用 print(__doc__)
d6ecd70965dba2f80d101c5104c4d0dfb3b6f8f8
rogers228/Learn_python
/note/module/12_multiprocessing/test_mul_02.py
2,000
3.640625
4
#莫凡教學 import multiprocessing as mp import time #--------7 進程鎖lock def job7(v, num, lock): lock.acquire() # 鎖定 for _ in range(10): time.sleep(0.1) v.value += num print(v.value) lock.release() # 釋放 def multicore7(): #v 可視為公用變數 叫好理解 lock = mp.Lock() v = mp.Value('i', 0) ...
fbbfb67a5bfcaa03e1fdc0fdddbfba5a87faa34f
rogers228/Learn_python
/note/module/03_tkinter_圖形視窗介面/202209ttk/ttk_example_04_事件綁定.py
1,702
4.125
4
# https://www.pythontutorial.net/tkinter/tkinter-event-binding/ import tkinter as tk from tkinter import ttk ''' 事件名稱 語法為 <modifier-type-detail> modifier 修飾符 type 類型 detail 細節 詳細請參閱網址 ''' def return_pressed(event): print('Return key pressed.') def log(event): print(event) def test1(): ...
83d327acab0236f9d0625338f710497facb00f40
73ddr/practica_4
/task_3.py
84
3.546875
4
result = (i for i in range(20, 241) if not i % 20 or not i % 21) print(list(result))
6261a5021d2606e63ea6b914e4784a72a27f1bba
wbmedia/algortims-and-data-structures-in-python
/Listas.py
361
3.984375
4
# easy way MyList = [1, 2, 3, 4, 5, 6, 7, 8, 9] newList = [x ** 2 for x in MyList] myTuple = [(1, 2), (2, 3), (3, 4)] newTuple = [x ** y for (y, x) in myTuple] print(newList) print(newTuple) # old way for (x, y) in myTuple: newTuple.append(x ** y) print(newTuple) # filtering data newFilter = [x**y for(x, y)...
30f4f08b2ec210daf1b325fc29d0ff7ab4a1c3b6
AntoineTroncin/Project_IFP
/book.py
3,946
3.71875
4
class Order: def __init__(self, quantity, price, buy = True): self.quantity = quantity self.price = price self.buy = buy def __str__(self): return "%s @ %s" % (self.quantity, self.price) #o = Order(5, 11.0) class Book: def __init__(self, name, liste = []): self.na...
7eb32428650a5779d8a8236754e72ee9868fdef4
UNStats/gender_data_portal
/scripts/utils2.py
303
3.9375
4
def col_names_to_uppercase(x): ''' convert all columns in a dataset to uppercase input: x is a list of dictionaries ''' new_x = [] for i in x: newdict = dict() for k in i.keys(): newdict[k.upper()] = i[k] new_x.append(newdict) return new_x
2060de4479ae5a272946af6e136e88fe70cd8903
kosh1196/python-program
/letterfreq..py
594
4.09375
4
def get_letters_frequency(phrase): letters = "abcdefghijklmnopqrstuvwxyz" letters_frequency = {} for char in phrase: letter = char.lower() if letter in letters: if letter in letters_frequency: letters_frequency[letter] += 1 else: lette...
8ba8f49b3997baed5a92c3de146cb2704ce17044
alex9707/210CT
/Q2.py
1,213
4.46875
4
def trailingzeros(number): #function to calculate trailing zeros with variable number defined answer=1 #Will be used times with the input number while number>0: #while loop will iterate until the base case of zero is reached answer=answer*number #For each iteration the number will times by the de...
760762da80dee1acc4d331d9259c33cdc96067a5
notmanav/FinancialPlanner2.0
/retirement/utils.py
801
3.71875
4
from datetime import timedelta, date import calendar class DateUtil: def add_days(self,inthedate,thedays): return inthedate+timedelta(days=thedays) def add_months(self,txDay,inthedate,months): month = inthedate.month - 1 + months year = int(inthedate.year + month / 12 ) month ...
b393b7501f9261cf6d521a1f91c4ccf79ffa02be
nghianja/Coffee-Machine
/Coffee Machine/task/machine/coffee_machine.py
4,151
4.03125
4
class CoffeeMachine: def __init__(self): self.ml_of_water = 400 self.ml_of_milk = 540 self.grams_of_beans = 120 self.disposable_cups = 9 self.money = 550 self.state = "action" def check(self, water_per_cup, milk_per_cup, beans_per_cup, cost_per_cup): if s...
ccd827058cc5c861fea7a07992ff30d116e6d17d
scotthaleen/python-secret-sauce
/src/generators.py
443
3.5625
4
# -*- coding: utf-8 -*- from functions import inc ''' generators ''' def numbers(start=0): n = start while True: yield n n = inc(n) def AZ(): for n in range(65,91): yield chr(n) def az(): for n in range(97,123): yield chr(n) def alphanumeric(): for n in range(0,1...
2a274f8bf165a7fa55c96e3289674d25a65ec904
mattrasto/ProjectVerano
/abs_min_max.py
514
3.515625
4
# Returns results in format: # {"DATE": "__DATE__", "ACTUAL": __MIN_PRICE__}, {"DATE": "__DATE__", "ACTUAL": __MAX_PRICE__} def abs_min_max(data, algo_code): data_max = data[0] data_min = data[0] for dct in data: if dct[algo_code] > data_max[algo_code]: data_max = dct if dct[algo_code] < data_min[algo_code]...
db8c28a903bcb5087be8d378bbf5ce11b33ff1e4
magibeg/Python
/Random Short Programs/VariousCalculations.py
531
4.09375
4
#Does various calculations area = 0 height = 10 width = 20 #calculate the area of a triangle area = width * height * 2 print("The triange is " + str(height) + " tall and " + str(width) + " wide.") #print formatted float value with 2 decimal places print("The area of the triangle is %.2f" % area) print("The area of th...
07f195b73386d359baa56a6817b748633af2644d
magibeg/Python
/Random Short Programs/StringsAndVariables.py
307
4.125
4
#A somewhat structured collection of strings and variables print("Welcome to the strings and variables program!") name = input("What is your name?") country = input("What country are you from?") print(country.upper()) print(country.capitalize()) print("Your country is " + len(country) + " letters long")
99f4c591954b38e160cefab21a1d4e84557c923c
magibeg/Python
/AutomateTheBoringStuff/Chapter 4/CommaCode.py
286
3.734375
4
#Contains a function that takes a list and outputs CSV values def toCommaCode(theList): for i in theList: print(i) return "{}, and {}".format(", ".join(theList[:-1]), theList[-1]) spam = ["apples", "bananas", "tofu", "cats"] newList = toCommaCode(spam) print(newList)
0f99e9724380d6ba633e54d776e0f5b8b3d51a5f
AndreyAAleksandrov/GBPython
/Algorythm/Lesson1_Task4.py
1,220
4.03125
4
# 7. По длинам трех отрезков, введенных пользователем, определить возможность существования треугольника, # составленного из этих отрезков. Если такой треугольник существует, то определить, является ли он разносторонним, # равнобедренным или равносторонним. a = int(input('Введите сторону А треугольника: ')) b = int(in...
f83b6828a5f7a0f265e3d525192391b90570484d
AndreyAAleksandrov/GBPython
/Algorythm/Lesson3_Task3.py
735
4.03125
4
# 3. В массиве случайных целых чисел поменять местами минимальный и # максимальный элементы. import random size = 10 list = [random.randint(0, 99) for _ in range(size)] print(f"Before : {list}") max = list[0] min = list[0] max_index = 0 min_index = 0 for index in range(1,size): if list[index] > max: m...
528900f84d349bef92fd1144c5485627d6118cd9
AndreyAAleksandrov/GBPython
/Algorythm/Lesson3_Task1.py
477
3.9375
4
# 1. В диапазоне натуральных чисел от 2 до 99 определить, сколько из них # кратны каждому из чисел в диапазоне от 2 до 9. for natural in range(2,10): result = [] for digits in range(2,100): if digits % natural == 0: result.append(digits) print(f"Для числа {natural}, количество кратных {...
f521436d0fc5202a9d5439373ed682258de87134
Sadidadri/ejerciciosPOO1
/python/Relacion1ObjetosPython/TestFraccion.py
1,115
3.640625
4
# coding=utf8 ''' Created on 17 ene. 2019 Prueba Clase Fraccion @author: d18momoa ''' from Relacion1ObjetosPython import Fraccion #main: fraccion1 = Fraccion.Fraccion(4,24) print("Fraccion 1:") print(fraccion1.mostrarFraccion()) print("Fraccion 1 simplificada:") fraccion1.simplificaFraccion() p...
8feff0002201326848358d9d38f8d8b8691724c2
codebrotherone/CodeJamProblems
/ProblemA_Round3_2017/main.py
2,854
3.84375
4
""" Problem A. Round 3 2017 CodeJam Challenge This module will process strings and determine if they are googlements. Details on googlements can be found in README.md in current directory. It will contain the following funcs: - decay() - handleEdgeCases() """ def decay(num_str, num_len): """This function will ...
c6c0064bd901f80ca49e05a5a7fbcde1e3a9cb16
utkarsh-27-sharma/DSA
/HackerRank/function.py
247
4.0625
4
def is_leap(year): leap = False # Write your logic hedef is_leap(year): if (year%4==0): leap = True if(year%100 ==0): leap=False if(year%400==0): leap=True return leap
c48cb695a67b4b413ffac56cb96868665d74c7ba
utkarsh-27-sharma/DSA
/HackerRank/find_angle.py
285
3.828125
4
# Enter your code here. Read input from STDIN. Print output to STDOUT import math import io import sys sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') L=[int(input()) for i in range(2)] s = str(int(round(math.atan2(*L)/math.pi*180,0))) print(s, end='') print('°')
b9349a83ec09b53700542aae3587170696469620
abhishekreddy1206/spoj
/fctrl.py
173
3.625
4
pows = [5**x for x in xrange(1, 15)] T = int(raw_input()) for _ in xrange(T): N = int(raw_input()) res = 0 for pow in pows: res += N / pow print(res)
e3862a6af6575a80e1dcfa9cd8fdb73c427d8604
pmsorhaindo/adventOfCode2019
/day1/day1.py
331
3.71875
4
import math f = open('input.txt', 'r') y = 0 def calculate_fuel(mass): fuel = calculate_fuel_for_mass(mass) if calculate_fuel_for_mass(fuel) > 0: fuel = fuel + calculate_fuel(fuel) return fuel def calculate_fuel_for_mass(mass): return math.floor(float(mass) / 3.0 ) - 2 for x in f: y += calculate_fuel(x...
8373fc2d13bdfc531efb2f5b4965ce2605bda01e
eric-baack/cs160
/exercises/oob/Point.py
2,004
4.15625
4
""" Point.py """ # Feb 13 2019 import math class Point: """ Class POint x and y must be integers """ # this is the doc string, under function def __init__(self, _x, _y): #need to have reference to object itself - self (usually - not keyword) in python; 'this' in other languages self._x ...
ea999ee81820144688c70a8d79fb74b164032cac
eric-baack/cs160
/exercises/sorting/sortingo.py
2,821
4
4
""" Sorting.py April 4, 2019. E. Baack Sort list of integers using selection sort, bubble sort, merge sort, quicksort, or heapsort """ def bubble_sort(alist): """ implementation of bubble sort""" for passnum in range(len(alist)-1,0,-1): for i in range(passnum): if alist[i]>alist[i+1]: ...
0ba1d5825af5539d1b5016719eb54a4f172603e8
eric-baack/cs160
/projects/customproblem/customproblem.py
13,250
3.640625
4
#!/usr/bin/env python3 """ customproblem classes """ """ implement a seed bank database each set of seeds is an accession, which includes collection lat, long, year. Each accession has taxonomy (genus, species) which has family (family, alternative family) each accession can be crop (includes breeder, disease resistan...
590dfa95ae2ee20eb5249b494168f640ffb9828a
eric-baack/cs160
/projects/dice/dice_classes.py
2,969
3.75
4
#!/usr/bin/env python3 """ Dice game(s) simulator """ import random from typing import Sequence random.seed(42) class Die: """Class Die""" def __init__(self, possible_values: Sequence) -> None: """Class Die constructor""" self._all_values = possible_values self._value = random.choice...
7cebb79d5d4f8fca6749578b5ee385fcf633e30d
eric-baack/cs160
/projects/keyboard/keyboard.py
3,678
3.890625
4
#!/usr/bin/env python3 """ Touchscreen Keyboard """ # create a map of the keyboard in order # to find distances # How? Dictionary? Letter - followed by XY coordinate # eg A = 1,2. B = 5,1. C = 3,1. D = 3,2. # And D = abs(diff(x)) + abs(diff(Y)) # OK, how to do this in a dict? Probably not: two dimensions, need ...
0934c607ae5bbac6f1776318542f1f348c7dc8a8
eduruiz333/python
/listas-manipulacao.py
1,476
4
4
primos = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] print(primos[5:10]) print(primos[:10]) print(primos[15:]) print(primos[:]) # Isso cria um CLONE da lista print() lista1 = ['vermelho', 'verde', 'azul'] lista2 = lista1 print(lista2) lista2[0] = 'rosa' print(lis...
632c42ab1335b70770269001153fa36252fcff09
eduruiz333/python
/while.py
159
4.0625
4
quantasVezes = int(input('Digite a quantidade de vezes que quer calcular a potencia de 2: ')) i = 0 while i <= quantasVezes: print(2 ** i) i = i + 1
ed6365ed3f4ddaf114ea2726aa34659596a37df8
danbatiste/PElib
/PElib/iter_lib.py
309
3.546875
4
# iter_lib.py def remove_duplicates(elements): """Returns a copy of the input list without duplicates removed. EX: remove_duplicates([1,2,3,3,4,4,4]) -> [1,2,3,4] - elements: The input list remove_duplicates(elements: list) -> list""" return list(set(elements))
34847967bd555240c2c38e2da624ba2f95dab66f
jakegerard18/Python-Datastructures-and-Algs
/LinkedList.py
2,192
3.734375
4
from Node import Node class LinkedList: def __init__(self, startingNode = None): if startingNode: self.head = startingNode self.tail = startingNode self.size = 1 self.head = Node() self.tail = Node() self.size = 0 def addToHead(self, node): ...
370b86b8eeba3e762b59e3e789dd6460cfe4e742
DmY39/Course-2-continue
/3.3.Step 7.Str.py
2,835
3.65625
4
# Выведите строки, содержащие "cat" в качестве подстроки хотя бы два раза. # import sys # import re # # for line in sys.stdin: # line = line.rstrip() # if len(re.findall(r"cat", line)) > 1: # print(line) # Выведите строки, содержащие "cat" в качестве слова. # import sys # import re # # for line in sy...
aa0ef016a4a3c48cb5061b6ae0f9108cf17271c7
nanorepublica/hokodo-test
/exercise5.py
270
3.84375
4
#!/usr/bin/env python3 from collections import Counter def main(): val = input('> ') counter = Counter(val.split(' ')) for item, count in sorted(counter.items(), key=lambda x: x[0]): print(f"{item}:{count}") if __name__ == '__main__': main()
8a7a82760c7ad605b871547b129a4aec4cc332b8
IronSenior/PracticasUNI
/Tercero/ISSBC/Practica 5/rdflib/ej-rdflib-t-10.py
2,635
3.71875
4
# -*- coding: utf-8 -*- """ Created on Thu Mar 29 09:48:22 2018 @author: acalvo """ ''' Adding Triples We already saw in Loading and saving RDF, how triples can be added with with the parse() function. Triples can also be added with the add() function: Graph.add() Add a triple with self as context add() take...
20fa140e0e736183dabd841af89e064527569c8e
brontel/repo1
/student.py
1,350
3.953125
4
""" Design and implement a class named "Student" with three methods __init__(self, courseName) addCourseMark(self, course, mark) average(self) """ class Student: studentName = "" courseMarks = {} def __init__(self, name): """ Creates a new student with a name >>> myStudent = S...
61ca676243c3fa22fd96c905c4732f145a4823bf
dimon58/all_mipt_labs
/1sem(python)/lab3/bulldog.py
13,045
4.0625
4
from math import sin, cos, radians, sqrt, pi from random import random import pygame from pygame.draw import * from typing import Tuple, Union pygame.init() DEBUG = False FPS = 30 SCREEN_WIDTH, SCREEN_HEIGHT = 800, 800 screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) screen.fill((255, 255, 255)) d...
f235c39b3819518b10d216212e40fb16507b1474
joshseymour/python-challenge
/PyPoll.py
2,311
3.84375
4
#import libraries import os import csv #set file path csvpath = os.path.join("Resources", "election_data.csv") #create counters votes = 0 winning = 0 #create list without headers data = [] #create list of candidates candidates = [] #create dictionaries of candidate votes & percentage of votes candida...
1c62fc977f4b4f03aa03e47f5bfa24a72b8baa74
davejonesbkk/house_sales
/house_sales.py
538
4
4
""" 2: Given a CSV listing homes sold, the sale date, and the ZIP code of the home, write a script to print out how many homes were sold each day. 3: Building on question 2, expand that script to break down the homes sold per day by ZIP code. Your output should look like: Date,76325,789123,54375 07/13/2018,4,0,2 08/04/...
ec24371bc7d7749c9dd5b4075296b95fdd01623a
Praveenstein/numpy_pandasProject
/main_moving_mean_q8.py
1,270
3.734375
4
# -*- coding: utf-8 -*- """ Find SMA, EM of Given Array Main ========================================== Main Module for finding the simple moving average(SMA), expanding window average(EM) of Given Array This script requires the following modules be installed in the python environment * logging - to perform loggi...
8f4ef0386ab7ccfb592604a07879767627177258
saraswatAshish/tathastu_week_of_code
/day1/program1.py
307
3.75
4
name = input('Type your name:') branch = input('Type your branch:') gender = input('Type your gender:') collegeName = input('Type your college name:') age = int(input('Type your age:')) print('Name:',name) print('Branch:',branch) print('Gender:',gender) print('College name:',collegeName) print('Age:',age)
00faa99c60305f5be1c6451ecb70971e232a3c52
Elijah-M/Module9
/definitions/set_ops.py
184
3.515625
4
def print_set(the_set): """ This function prints a set, which is received through the parameter :param the_set: :return: """ for x in the_set: print(x)
7f754fdb0642ec0e1f23d091daf16a8900b627e3
typ8008/Algorithm
/Exam.py
2,843
3.859375
4
# -*- coding: utf-8 -*- """ Created on Sat Apr 4 21:16:55 2020 @author: Mariusz """ import math var1 = 7 def var3(var1, var2): var0 = var1 + var2 var1 += 1 print var1 global var4 var4 = 17 print locals() return var0 + var4 print var3(var1, var1) #global_dict = {} #global_dict[(0)] = ...
cba283fd31aafe18961b4af83d39d3e6e1837b17
CizChenzhoU/myPython
/myPyCharm/Process/Itertools.py
2,286
4.15625
4
# python的内建模块itertools提供了非常有用的用于操作迭代对象的函数 # 首先,我们看看itertools提供的几个‘无限’迭代器 # import itertools # natuals = itertools.count(1) # for n in natuals: # print(n) # # 因为count()会创建一个无限的迭代器,所以上述代码会打印出自然数序列,根本停不下来,只能按Ctrl+C退出。 # # cycle()会把传入的一个序列无限重复下去: # import itertools # cs = itertools.cycle('abc') # for n in cs: # p...
db58b7d9b1e453e65b7cc1071b4e8a4260643577
BenGilbert98/python_OOP
/animal.py
811
4.21875
4
# Creating an Animal class as PARENT / BASE / SUPER class class Animal: def __init__(self): # initialising the Animal class self.alive = True # Creating an attribute / variable self.spine = True self.lungs = True self.eyes = True # Create behaviours as functions / methods ...
9c5fd063ca398e0b4e06df07fb32e07f169901a9
AsturCal/MiniMaxTicTacToe
/minimax.py
5,303
3.90625
4
#Tic-Tac-Toe Minimax. #Plays player vs. Player or Player vs. COmputer. #used to study traversing the tree... class GAME: def __init__(self): ''' Initialize board , moves stack and winner.''' self.board = ['-' for i in range(0,9)] self.lastmoves = [] #breadcrum self.winner = None def print_board(self...
437ecd0a67cdc1dca2da6e6b32f95aafa585585a
priyapriyam/loop_question
/ankita.py
62
3.578125
4
list=[4,9,8,7,6,3,3] i=1 while i<len(list): i=i+1 print(i)
2df1ca18d1794067ff78f1276d9ef445a720a53f
edurs99/python-udemy
/trabalhando_com_arquivos/assignment_answer_file_processing2.py
495
3.875
4
# with open('devices.txt', 'r') as f: # devices = f.read().splitlines() # #print(devices) # # criando uma lista # mylist = list() # # criando um for, onde eu defino o campo delimitador e adiciono o conteudo na lista # for item in devices: # tmp = item.split(':') # mylist.append(tmp) # print(mylist) imp...
2ffd25a0ef5336a0e7d548f34ac3ba0e47cf8a71
edurs99/python-udemy
/trabalhando_com_arquivos/calling-tail-function.py
393
3.984375
4
def tail (file,n): with open ('sample_file.txt','r') as f: # reading the file in a list content = f.read().splitlines() # getting the last element of the list last = content[len(content) -n:] print(last) # concatenating the list back into a string my_str = '\n...
ec863fff5791634c4f7e65e5a770bbebd4000b64
edurs99/python-udemy
/data_serialization/challange_json_csv.py
1,267
3.546875
4
def serialize(obj, file, type): if type == 'pickle': import pickle with open(file, 'wb') as f: pickle.dump(obj, f) elif type == 'json': import json with open(file, 'w') as f: json.dump(obj, f) else: print('Invalid serialization. Use pickle or j...
1d4da5b4b922eb6310cd9d2666dc3cfc974a4a36
sonypark/Algorithm-playground
/boostcamp/테스트2.py
1,271
3.765625
4
from collections import Counter def eval_pairs(arr): c = Counter(arr).most_common()[0] val_of_pairs = c[0] num_of_pairs = c[1] return [val_of_pairs, num_of_pairs] def solution(arr1,arr2): val_of_pair_arr1, num_of_pair_arr1 = eval_pairs(arr1) val_of_pair_arr2, num_of_pair_arr2 = eval_pairs(arr...
4ae42c2c0c5693b4a8d56ffd8123f42f8cef5205
Alex-Sjoberg/Rogue-Space
/Rogue Space/item.py
390
3.65625
4
''' Created on Mar 17, 2013 @author: asjoberg ''' import tile class Item(): def __init__(self,name = "Item", number = 1): self.number = number self.name = name self.description ="This is an object of some kind. You don't know what it is." self.tile = tile.Tile() ...
50255a6f6fab4d1c0016f911d01aefe35f913194
Subham47/Python-learning-week3
/assign_solutions/problem3_3.py
344
4
4
def problem3_3(month, day, year): """ Takes date of form mm/dd/yyyy and writes it in form June 17, 2016 Example3_3: problem3_3(6, 17, 2016) gives June 17, 2016 """ atup=("January","February","March","April","May","June","July","August","September","October","November","December") print(atup[mon...
06173f45e19700a2f91fd030606fa699a8da304f
ivanbgd/Coursera-Neural-Networks-for-Machine-Learning-in-Python
/AS2/train.py
12,347
3.53125
4
import numpy as np import sys from time import time from utils import * from fprop import fprop def train(epochs = 1): """ This function trains a neural network language model. Inputs: epochs: Number of epochs to run. Output: model: A struct containing the learned weights and bi...
a58795c5bcfa5ed9a0f0d6c394e0724c4ad07177
MicahJank/cs-module-project-iterative-sorting
/src/space_complexity.py
564
3.546875
4
n = [None] * 1000 ​ # O(1) def simple_function(n): return n ​ simple_function(n) ​ # O(n) def make_another_array(n): inner_array = [] ​ for i in n: inner_array.append(i) ​ return inner_array ​ make_another_array(n) ​ # O(n^2) def make_matrix(n): matrix = [] ​ for item in n: row =...