blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
2eb54ba715760ddfd135c441485c05fbafa97496
dindamazeda/intro-to-python
/lesson5/1.enumerate.py
340
4.15625
4
reverse_order = reversed(['a', 'b', 'c', 'd', 'e']) ordered_numbers = sorted([83, 3, 92, 22, 31, 83, 14, 54, 72]) for index, letter in enumerate(reverse_order): print('Letter {} has an index of {}'.format(letter, index)) for index, number in enumerate(ordered_numbers): print('Number {} has an index of {}'.for...
8900a828899fa198a729ac7b4d1234ed84045c12
PotentialStyx/advent-of-code-2020
/days/02.py
1,020
3.5
4
from collections import Counter def part1(data): data = data.split("\n") def map_it(data): final = [] data = data.split(":") final.append(data[0].split(" ")[0]) final.append(data[0].split(" ")[1]) final.append(data[1][1:]) return tuple(final) data = list(map(map_it,data)) total = 0 for i in data: ...
d80332612265bfd24b9506ed36c17536c47a8d9e
maranemil/howto
/datamining/machine_learning_py_scripts/classifiers_ipynb2py/Mini_Project_Logistic_Regression.ipynb.py
25,971
3.78125
4
# coding: utf-8 # # Classification # $$ # \renewcommand{\like}{{\cal L}} # \renewcommand{\loglike}{{\ell}} # \renewcommand{\err}{{\cal E}} # \renewcommand{\dat}{{\cal D}} # \renewcommand{\hyp}{{\cal H}} # \renewcommand{\Ex}[2]{E_{#1}[#2]} # \renewcommand{\x}{{\mathbf x}} # \renewcommand{\v}[1]{{\mathbf #1}} # $$ # *...
35d28ac145fab5b2e8cfb381eecb28511dd00c05
UN-FISICA/taller-2-2018-2-judhernandezra
/Ejercicio5.py
472
3.53125
4
#!/usr/bin/python # -*- coding: utf8 -*- import math import turtle np= input("Número de filas de la pirámide ") turtle.penup() turtle.lt(90) turtle.fd(200) turtle.rt(90) turtle.pendown() for j in range(np+1): i=-j+1 ang=360/(j+2) while -j<i<j: turtle.penup() turtle.goto(i*10*np,200-(15*np*(j-1))) turtle...
a9b15ac8e2a884d59179d31942976444106f2aa7
stephanosterburg/coding_challenges
/codewars/add_binary.py
415
4.25
4
# Implement a function that adds two numbers together and # returns their sum in binary. The conversion can be done # before, or after the addition. # # The binary number returned should be a string. def add_binary(a, b): return bin(a + b)[2:] print(add_binary(1, 1)) # "10" print(add_binary(0, 1)) # "1" print(a...
b52ac1ee1a804c585008c154c2a46e5db4471e7c
Rxma1805/LintCode
/415. Valid Palindrome/验证回文字符串.py
591
3.8125
4
class Solution: """ @param s: A string @return: Whether the string is a valid palindrome """ def isPalindrome(self, s): # write your code here s = s.lower() i=0 j=len(s)-1 while i < j: if not s[i].isalpha() and not s[i].isdigit(): i...
93a8739aadff27f7ae9c5cf88b117447e3d5d446
qiaojianjunjojo/learning_node
/201812月python/canvas_oval.py
404
3.515625
4
import tkinter as tk from tkinter import messagebox window = tk.Tk() window.title('my test window') window.geometry('1200x800') x = 360 y = 160 top = y - 30 bottom = y - 30 canvas = tk.Canvas(window,width = 500,height = 600,bg = 'white') for i in range(20): oval = canvas.create_oval(250 - top,250 - bottom,250 + ...
6090231035ce5299f5486f9a9848e6eb5b871d63
JeromeLefebvre/ProjectEuler
/Python/Problem016.py
355
3.875
4
#!/usr/local/bin/python3.3 ''' Problem 16 215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2**1000? ''' from pe.digits import applyToDigits def problem16(): return applyToDigits(2**1000) from cProfile import run if __name__ == "__main__": print(problem1...
667f9a53063b3eadb5160f2ec3f260a3ff0f1453
omkar-zare/daily-programming
/top_microsoft/588-design-in-memory-file-system.py
1,415
3.65625
4
""" Design a data structure that simulates an in-memory file system. Implement the FileSystem class: FileSystem() Initializes the object of the system. List<String> ls(String path) If path is a file path, returns a list that only contains this file's name. If path is a directory path, returns the list of file and dir...
ef1b33f0af1f092f62e29d0cf2219a8eabc36ba3
maxsorto/PythonInformatics
/exam2-1.py
755
3.765625
4
""" Name: Max Sorto Class: IT 5090G - Aasheim Due: Apr. 14, 2016 Exam 2 """ lines = open('sales1.txt') # Read text file sales = [] # Create empty list for sales # Loop through sales and append the sale value to the list for line in lines: line = line.split(' ') sale = line[2] sale = float(sale[1:]) sales.append...
4766c73650ec1fa1db88f63126a507911cf4cc0c
imaldiris/folder-for-work
/ex24.py
5,842
3.640625
4
def string_splinter(data, strings, length, count): """Представление "колец" матрицы в ввиде прямоугольника и разворот прямоугольника (верхнее основание, правая сторона, нижнее основание(инфвертированное), левая сторона(инфвертированная) - порядок разворота) в прямую.""" sub_string = '' if (count - 1) *...
d61f745d02964b9c4ff5ac538546b286faa288dd
olgar22/Data-Science-Position-Compensation
/Project_2_data_scraping.py
718
3.515625
4
import pandas as pd from bs4 import BeautifulSoup import requests def data_scrape(**record): job_element = (record['job']).replace(' ', '%2B') state_element = record['state'] years_element = record['years'] url = 'https://www.dice.com/salary-calculator?title='+job_element+'&location='+state_element+'...
f999878df95ef9480d023d4ed065eaf3a58a549b
Hanumanth-Reddy/265101_Python_Miniproject
/hangman.py
4,305
3.96875
4
# pylint: disable=C0114 import sys import random from time import sleep # Hangman game with Words from file. # No of spaces are fetched dynamically according to word length. # features: admin and player. # used modules time,sys,random. name = input("UserName: ") WELCOME = "Hello, \"{n}\"".format(n=name) print(WELCOME...
71c47b1afc0e8f538192f61d14f796f424d09793
code-tamer/Library
/Business/KARIYER/PYTHON/Python_Temelleri/functions.py
1,347
3.53125
4
# def sayHello(): # print('Hello') # sayHello() # def sayHello(name): # print('Hello ' + name) # sayHello('İlker Batu') # def sayHello(name = 'user'): # print('Hello ' + name) # sayHello() # def sayHello(name = 'user'): # return 'Hello ' + name # msg = sayHello('İlker Batu') # print(msg) # d...
a1895c7785c1a6aeaa7bbb967654073b7f2161fa
krstoilo/SoftUni-Fundamentals
/Python-Fundamentals/Homeworks-and-labs/data-types-and-variables/convert_mr_to_km.py
74
3.578125
4
meters = int(input()) kilometers = meters/1000 print(f'{kilometers:.2f}')
3cb6780bc528d70c562f7112694586f7b87dbd64
daniel-reich/turbo-robot
/kzZD8Xp3EC7bipfxe_0.py
613
4.28125
4
""" Create a function that outputs the result of a math expression in words. ### Examples worded_math("One plus one") ➞ "Two" worded_math("zero Plus one") ➞ "One" worded_math("one minus one") ➞ "Zero" ### Notes * Expect only the operations `plus` and `minus`. * Expect to only get number...
5a5df131c0d1054c9b5fefa3d815a50cddb023c3
jimezo/TempR
/bubble_sort.py
618
3.6875
4
import random, time # Кол-во элементов COUNT = 40000 # Пустой список array = [] # Заполнение списка print('start append list') for element in range(COUNT): array.append(random.randint(0, 1000)) print('end append list') start_time = time.time() # Сортировка списка print('start sort list') k = 1 while k < len(ar...
f850aed56b0f8dacf57616dee5ea10716692dc02
CraxY-Codes/cmp104
/assignment.py
1,593
3.953125
4
import math msg = input('what shape would you like to find the area?') #msg triangle if msg == 'triangle': base = int(input('what is the base?')) height = int(input('what is the height?')) area = 1/2 * (base * height) print('the area of {}= {}'.format(msg, area)) #msg rectangle elif msg =...
6b524ae217c819e8c85ad90bd041d7dfcfb1ec14
vidhisharma1212/python
/ch6_07_ps.py
212
3.96875
4
post= input("Enter a post here : \n") if "harry" in post : print("yes! it is talking about harry") elif "Harry" in post : print("yes! it is talking about harry") else: print("no, harry not in post")
8f294d9980b2c7dbb3d2dd892f0e8fe67d03eca8
mikegoodspeed/euler
/020.py
283
3.796875
4
""" import operator def factorial(n): return reduce(operator.mul, range(1, n + 1)) def sum_digits(n): return sum(map(int, str(n))) print factorial(100) print sum_digits(factorial(100)) """ print sum(map(int, str(reduce(lambda x, y: x * y, range(1, 100 + 1)))))
aff13c409498a2aae296abc61da546e75a647ea3
EmbraceLife/LIE
/numpy/arange.py
1,706
3.859375
4
import numpy as np arange1 = np.arange(start=-5, stop=10, step=1, dtype='int32') # int32 arange2 = np.arange(start=-5, stop=10, step=1., dtype='int32') # int32 arange3 = np.arange(start=-5, stop=10, step=1., dtype='float32') arange4 = np.arange(start=-5, stop=10, step=.8, dtype='float32') # last value beyond 9 print(...
af6d7c48370018192ef3b5acf24201e2f3b55d0b
Swawm/game-idea-generator
/generator.py
8,020
3.609375
4
from tkinter import * from tkinter import messagebox import random def show_message(): if (message.get() == "") or (int(message.get()) > 100): messagebox.showinfo("Ошибка", "Введите количество механик < 100") elif int(message.get() == 0): messagebox.showinfo("Ошибка", "Удачи с этим") ...
64d69a3e06f8223767041ea3f3e597b4ee6f5353
lsankar4033/programming_gym
/hackerrank/sherlock_and_valid_string/run.py
836
3.734375
4
from collections import defaultdict def count_map(iterable): counts = defaultdict(lambda: 0) for x in iterable: counts[x] += 1 return counts def is_valid(s): char_counts = count_map(s) counts_of_counts = count_map(char_counts.values()) if len(counts_of_counts.keys()) < 2: ret...
a553a1acc0a34d8dd36a42be8d087c2778ee8a63
richie-edwards/practice-problems
/interview-cake/merging_meeting_times.py
1,049
3.6875
4
class Solution(): def merge_meetings(self, meetings): sorted_meetings = sorted(meetings) merged_meetings = [sorted_meetings[0]] for current_meeting in sorted_meetings[1:]: last_merged_meeting = merged_meetings[-1] if self.check_merge(last_merged_meeting, current_meet...
71dc8129794a35649a39e5954040bb65f10bd343
Gborgman05/algs
/py/prune_tree.py
1,218
3.875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: def contains_one(root): ...
3e1c7f29686c7ea4a85750f8aaa050bc4eefb8a2
penghit/leetcode
/DivideAndConquer/23-merge-k-sorted-list.py
800
3.96875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: # create a list to store all the elements in the node numlist = [] ...
ce6dfd183ee13f2179fdf3050996d8c643389b44
Ahmed--Mohsen/leetcode
/move_zeroes.py
935
4.09375
4
""" Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. Note: You must do this in-place without making a copy of the array. Minim...
d70c61117d677997720324e3959261b4e6020f2e
RazK/Intro2CS
/ex4/hangman.py
7,032
4.1875
4
#!/usr/bin/env python3 ############################################################# # FILE : ex4.py # WRITER : Raz Karl , razkarl , 311143127 # EXERCISE : intro2cs ex4 2016-2017 # DESCRIPTION: A Pythonic version Of The Game Hangman ############################################################# from hangman_helper impor...
1489b94055a83c421d0465c1042c04ca1ec36dc2
alexandraback/datacollection
/solutions_2453486_1/Python/vuamitom/tictactoe.py
2,017
3.5
4
def solve_tictoe(board): """solve a tic_toe of 4x4""" has_empty = False row = [0,0,0,0] col = [0,0,0,0] diagon = [0,0] t_pos = None for r in range(0, len(board)): for c in range(0, len(board[r])): #check row val = board[r][c] if board[r][c] == 'X...
dc2b8f216cec1ddf2fa9044c922b56a5311d5df5
bakienes/Python
/Source Code/english_turkish_dictionary.py
2,225
3.671875
4
#English Turkish Dictionary import os kelimeler = { "get":["Almak","Edinmek","Olmak","Elde etmek"], "break":["Mola","Ara","Kırılma","Fren"], "winner":["Kazanan","Galip","Birinci"] } def kelimeEkle(kelime,kelimeler): if kontrol(kelime,kelimeler): mevcut_anlamlar = set(kelimeler[kelime]) yeni_giriş= in...
746e0392050dc2e0cbb2abb624474f6fe1524aca
Kunal352000/python_program
/111.py
170
3.859375
4
for r in range(7): for c in range(5): if c==0 or c==4 or r==3: print("*",end=" ") else: print(" ",end=" ") print()
5815e5fb46da6ad2bc6c0a1c08984148b135a298
nyu-compphys-2017/hw1-atm426
/mandelbrot.py
1,913
3.640625
4
import numpy as np import matplotlib.pyplot as plt def main(S, N): """ makes a density plot of the Mandelbrot set S : number of iteration steps for each point N : grid size """ z_binary, z_density = point_count(N, S) extent = [-2, 2, -2, 2] plt.imshow(z_binary, extent=extent, cmap='Greys') ...
bbd1c3493b22bb7532ef9495fcb558fb278fbc21
18242360613/leetcode
/leetcode/109_Convert Sorted List to Binary Search Tree.py
1,031
3.953125
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def build_tree(self,...
c6bfa88dc880139a3bbf72e3a51b5555ea4b0523
rogerpease/CodeSnippets
/Python/BlackJackSim/CardShoe.py
2,917
3.6875
4
#!/usr/bin/python3.6 import random suits = ['h','s','c','d']; ranks = [ 'A','2','3','4','5','6','7','8','9','10','J','Q','K']; # # Card Class # class Card: def __init__(self,rank,suit): self.Rank = rank self.Suit = suit def RankValue(self): if self.Rank == 'A': return 1; if s...
d0205b4f1c5c72bd50613f9f672298fc20875b10
Aasthaengg/IBMdataset
/Python_codes/p03289/s745163586.py
200
3.8125
4
s = open(0).read().rstrip() import re if len(s)>3 and re.fullmatch(r'A[a-z]+C[a-z]+',s): print('AC') elif len(s) == 3 and re.fullmatch(r'A[a-z]?C[a-z]?',s): print('AC') else: print('WA')
66cec0a7ac099cad604acba803e5ca5b52994c71
malgorzatazdunik/CardGames
/src/functions.py
2,621
3.546875
4
from src.Hand import Hand from src.Deck import Deck from src.Chips import Chips def take_bet(chips : Chips) -> None: """ To do: Function docstring """ while True: try: chips.bet = take_bet_input() except ValueError: print('Must input integer') else: ...
3d271f614b3d4f26722f16b1e81d594a5ff2f34d
Rodrigo-Sarmento/scriptsPython
/RaizquadradaPotencia.py
215
4.03125
4
n = float(input('Digite um número: ')) print('o dobro desse número é: {:.2f}'.format(n*2)) print('o triplo desse número é: {:.2f}'.format(n*3)) print('a raiz quadrada desse número é: {:.2f}'.format(n**0.5))
14c8c7869f249123a58547297b97edf9edaf1f25
mryyomutga/TechnicalSeminar
/src/day2-1026/test2.py
707
3.96875
4
# -*- coding: utf-8 -*- # リスト内包表記 # 例えば from __future__ import print_function import math l = [10, 20, 30, 40] print(l) # リストの要素をルートをとった値に変換したい場合 l[0] = math.sqrt(l[0]) l[1] = math.sqrt(l[1]) l[2] = math.sqrt(l[2]) l[3] = math.sqrt(l[3]) print(l) # 非常に面倒 l = [10, 20, 30, 40] print(l) # これで全部ルートに変換 L = [math.sqrt(x) f...
95bdfb10e2e87afa217229b52cc8deaa87a110c7
liyu10000/leetcode
/heap/#215.py
810
3.53125
4
# first try class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: nums.sort(reverse=True) return nums[k-1] # second try: different strategies of using heapq def findKthLargest(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int ...
d94f0af3c9c735768deec65abbaf35e3280f3670
tefsantana/COSTA-ALGO1-public
/Ejercicios/C05 - Listas - Administracion de Alumnos.py
4,936
4.375
4
''' Cree un programa que permita al usuario elegir entre las siguientes opciones: 1 - Agregar un alumno: debe solicitarse nombre, padrón y nota. 2 - Consultar aprobados: debe mostrar los alumnos con nota mayor a 4. 3 - Cantidad de alumnos totales y promedio general. 4 - Quitar a un alumno. 5 - Salir ''' opci...
e6e36e211307666aa9fd3c67cb5ce674d0d8f99d
gomtinQQ/algorithm-python
/codeUp/codeUp100/1095.py
827
3.5625
4
''' 정보 선생님은 오늘도 이상한 출석을 부른다. 영일이는 오늘도 다른 생각을 해보았다. 출석 번호를 다 부르지는 않은 것 같은데... 가장 빠른 번호가 뭐였지? 출석 번호를 n번 무작위로 불렀을 때, 가장 빠른 번호를 출력해 보자. 참고 배열에 순서대로 기록해 두면, 기록된 내용을 모두 검사해 가장 작은 값을 찾아내면 된다. 그런데, 가장 작은 값은 어떻게 어떤 것과 비교하고 찾아야 할까? 번호를 부른 횟수(n, 1 ~ 10000)가 첫 줄에 입력된다. n개의 랜덤 번호(k, 1 ~ 23)가 두 번째 줄에 공백을 사이에 두고 순서대로 입력된다. ''' n =...
efabc6fb54ac69721a8ed165f620ee6c58a45ba3
rfork/cti110
/P3HW1_ColorMixer.py
1,967
4.375
4
# CTI-110 # P3HW1 - Color Mixer # Katie Rutherford # 25Feb2019 # # Chapter 3 Exercise #7 (Color Mixer) # This program displays the secondary color that would be created from 2 # primary colors, input by the user # Pseudocode: # Get 2 colors from the user # If either color is not 'red', 'blue', or 'yellow', display...
91efeda70cfaba3c5f5fdfdef2222c7810675094
JaimeMatias/Inteligencia-Artificial
/Subconjunto/subconjunto.py
2,471
3.546875
4
#!/usr/bin/python # -*- coding: latin-1 -*- import copy as cp def subconjuntoclase(archivo): """ devuelve un arreglo, donde para cada elemento de la clase, indica la cantidad de ocurrencias que tiene dentro del archivo El orden va a coincider con el orden en que aparecen en los datos. :param arch...
7a2bbad0db5dfae1ca47ba1476200f6c4ab3137c
braydonburn/robust_headgear
/Source/mySokobanSolver.py
26,133
3.640625
4
''' The partially defined functions and classes of this module will be called by a marker script. You should complete the functions and classes according to their specified interfaces. ''' import search import sokoban import sys # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -...
5362f0f7f3278798daeeceba73c90307147496ae
AmandaMoen/StartingOutWPython-Midterm
/weight_classes.py
1,334
4.21875
4
# Mid-term (refer to grader.py pg. 135-137 # Amanda L. Moen # amandalmoen@yahoo.com # Programming Exercises # 1) You are to write a program that reads in a boxer's weight and # report back to which weight class they belong based upon the following # table (e.g., 141-160 is the Welterweight class): # Weight Limits: ...
07960ab1cd6060e52a2f6c3bc403de728e226045
AsinRay/py
/src/db/testMySQL.py
1,234
3.890625
4
#!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("47.98.56.206", "root", "123456", "blz") # prepare a cursor object using cursor() method cursor = db.cursor() # execute SQL query using execute() method. cursor.execute("SELECT VERSION()") # Fetch a single row using fetchone() method....
21309d03f0dda766dd8f074ef061c680a645e1a2
Abhijeet-AR/Rubik-s-Cube-Solver
/rcube_solve_begginers.py
27,830
3.65625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu May 2 13:38:10 2019 @author: AR """ #from rubiks_cube import Cube class Solve: def __init__(self, blue, red, green, orange, white, yellow, shift, isSolved): self.blue = blue self.red = red self.green = green ...
bd4d9f69906b35ac0eb54bc14ff3b7158d001be8
phamhovinh/baithuchanh1
/kc 2 diem.py
248
3.515625
4
import math x1=int (input("nhap x1:")) y1=int (input("nhap y1:")) x2=int (input("nhap x2:")) y2=int (input("nhap y2:")) d1=(x2 - x1) * (x2 - x1); d2=(y2 - y1) * (y2 - y1); kc=math.sqrt(d1+d2) print("khoang cach giua 2 diem:",kc);
b4f6c7b441326b39eb94f91eec95b863b7711254
D-cyber680/100_Days_Of_Code_Python
/Day26-ListComprehension/Challenge_4.py
378
3.75
4
import random #new_dict = {new_key:new_value for (key, value) in dict.items() if this_is_true} names = ["Alex", "Beth", "Caroline", "Dave", "Eleanor", "Freddie"] student_scores = {student:random.randint(1, 100) for student in names} passed_students = {student:score for (student, score) in student_scores.items() if ...
80977c3548b801761dfaac11a385cf502338700f
kasunvj/Muti-Threading
/threading_5.py
605
3.84375
4
import threading def do_this(): global x, lock lock.acquire() try: print ("This is our Thread 1") while x<300: x +=1 print (x) finally: lock.release() def do_after(): global x,lock lock.acquire() try: print ("This is our Thread 2") while x<600: x +=1 print (x) finally: lock.releas...
ef704d03637df1f023ab96fbcef51f62b620f890
NickmBall1/Python
/python 5.py
590
3.765625
4
import random bn=0 gn=0 bad=0 gad=0 choice = input("Boy (b), Girl (g) or Quit (q): ") while (choice!='q'): if choice== 'b' : b=random.randint(1,40) bn+=1 bad+=b print("Boy score:" ,b) choice = input("Boy (b), Girl (g) or Quit (q): ") elif choice==...
9e738f74aa3309af80b055123943cb2df7f864af
gioporta/python_stuff
/pwmanager.py
676
4.375
4
#!/usr/bin/python3 # Password manager # This program will store passwords for each account name # Running account name as argument will put its password into clipboard # Insecure! There is no file encryption involved import sys, pyperclip passwords = {'email': 'emailpasswordhere', 'blog': 'blogpasswordhere', ...
89ca1ac4c0ce55ba5aba9fc477e8c2e703c83257
Pramod123-mittal/python-prgs
/str_two.py
275
4.15625
4
mystr = 'my name is Bhai' # some function of string print(mystr.isalnum()) print(mystr.endswith('i')) print(mystr.count('i')) print(mystr.index('i')) print(mystr.capitalize()) print(mystr.find('B')) print(mystr.upper()) print(mystr.lower()) print(mystr.replace('is','are'))
e52550ff79d725174121f140139b27b509e2c658
Six-S/Python-Coding-Challenges
/RedditChallenges/challenge1.py
2,132
3.765625
4
#Written by: (Six-S) #Challenge #380 Smooshed Morse Code 1 #https://www.reddit.com/r/dailyprogrammer/comments/cmd1hb/20190805_challenge_380_easy_smooshed_morse_code_1/ class Morse(): def __init__(self): #a-z in morse code. #include '' to handle sentences. self.morse_list = { 'a'...
4e56d2e89af51c9c7a5ad09e6f686140eac62567
eclairsameal/TQC-Python
/第1類:基本程式設計/PYD110.py
281
3.625
4
from math import pi, tan, pow n = eval(input()) s = eval(input()) area = (n * pow(s, 2))/(4 * tan(pi/n)) print('Area = {:.4f}'.format(area)) import math n = eval(input()) s = eval(input()) area = (n * math.pow(s, 2))/(4 * math.tan(math.pi/n)) print('Area = {:.4f}'.format(area))
233b1fdc5f8c6b3cca09408b03b2dc8fd119045e
austinbruch/MinesweePy
/Board.py
1,159
3.765625
4
from Tkinter import Tk, BOTH, SUNKEN, RAISED, Frame, Button, Label class Board(Frame): def __init__(self, x_dim, y_dim, game, parent=Tk()): Frame.__init__(self, parent) self.game = game self.parent = parent self.x = x_dim self.y = y_dim self.initUI() def initUI(self): ...
8be0d38279c010fdca40b22cd03abdc69f9a15f0
yyyyj/Clara
/core/town/street.py
3,169
3.921875
4
__author__ = 'Folaefolc' """ Code par Folaefolc Licence MIT """ from .buildings import Building from ..life import person from ..life import time class Street: def __init__(self, name: str="", size: float=1.0): self.name = name self.size = size self.buildings = [] self.connections...
3b3252fc631abb03fda310653906dfc99c52b732
dongxiaohe/Algorithm-DataStructure
/algorithm/graph/topological-sort/solution.py
1,604
3.5
4
import collections def topologicalSort(graphs): visited, deque = collections.defaultdict(bool), collections.deque() for node in graphs: if visited[node]: continue dfs(node, visited, deque) return deque def dfs(node, visited, deque): visited[node] = True for child in node.children: ...
8a11352358405128d2a0624388cbf86353201d83
rgc292/final_project
/ReportCardGenerator/unittests/test_mode.py
654
3.5
4
''' Authors: Aditi Nair (asn264) and Akash Shah (ass502) These tests ensure that the program ignores case when accepting valid user input, that the program rejects invalid choices of user input, and that the program quits correctly. ''' from unittest import TestCase from mode import * class Interpret_Mode_Test(Test...
1bd247816282fe2778fa9b2e7ae4fc831ff42cf6
mmza/NeuralNet
/neural.py
3,906
3.671875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 19 13:25:56 2017 @author: mike """ import numpy as np class Perceptron: def __init__(self, w, b): self.w = w self.b = b def forward_pass(self, single_input): result = 0 for i in range(0, len(self.w)): ...
576868854ddbb2f37e17ee893955162498cc4a52
Ademolah/MyPrograms
/remote.py
551
3.546875
4
class RemoteControl: def __init__(self): self.channels = ['CN','sports HD', 'Imax', 'music'] self.index = 0 #the tv is off def __iter__(self): return self def __next__(self): self.index += 1 #meaning when the tv is on if self.index == len(self.chan...
e29bc32c37ad47bcfcd2b9ef86f02c2f38f7fbfa
StackedCrooked/stacked-crooked
/Playground/python-course/paccount.py
1,733
3.59375
4
import sys class Account(object): __slots__ = [ 'name', '_balance', 'min_balance', 'transactions', 'index' ] def __init__(self, name): self.name = name self._balance = 0 self.min_balance = 0 self.transactions = [] self.index = 0 def __iter__(self): return ...
0299565b037f9ceeff438f31b9b656c89665ec57
domahes88/domahes
/dop - 1 - n1.py
161
3.515625
4
# domahes import math pi = math.pi t0 = int(input()) t1 = int(input()) t2 = int(input()) s0 = pi*t0 s1 = pi*t1 s2 = pi*t2 print(s0, s1, s2) print(s2 - (s0 + s1))
5cc4f6793398d95ece710250c8bbb7c563d250e9
ditiansm2015/Python-Game_Projects
/Guess_the_number(Week 2).py
1,862
4.1875
4
# input will come from buttons and an input field # all output for the game will be printed in the console import random import simplegui secret_number=0 counter=0 # helper function to start and restart the game def new_game(): # initialize global variables used in your code here global secret_num...
452e5755bb04f5ccbd39374457086470f80ec832
qmnguyenw/python_py4e
/geeksforgeeks/python/easy/20_19.py
3,388
4.15625
4
Python | Pandas Dataframe.duplicated() Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. **_Pandas_** is one of those packages and makes importing and analyzing data much easier. An important part of Data analysis is analyzing _...
e07e71e3a6c5230651a34c43fe428b9fa331925b
THABUULAGANATHAN/playerlevel
/rangeorlong.py
151
3.640625
4
z11=int(input()) if(z11>=-2**15+1 and z11<=2**15+1): print('INT') elif(z11>=-2**31+1 and z11<=2**31+1): print('LONG') else: print('LONG LONG')
140477bba2fe429053e249a521ef435febb3349b
daniel-reich/ubiquitous-fiesta
/QuxCNBLcGJReCawjz_1.py
166
3.6875
4
def palindrome_type(n): b, d = [s == s[::-1] for s in [str(n), bin(n)[2:]]] return ['Neither!','Binary only.','Decimal only.','Decimal and binary.'][d + 2 * b]
62feebeb0d5c08d36d4a1a6d7cc69300ee3e5529
expressionsofchange/nerf1
/memoization.py
1,992
3.5
4
""" "There are only two hard things in Computer Science: cache invalidation and naming things." Here are some notes about one of those (caching). In a "nerfy context", there are a few things that we can use to make it less hard; but not completely trivial. In particular, we can use the fact that we can be precise abo...
566b48cc2e8bb585a29be42b38288d7208833987
ARUN14PALANI/Python
/NumberGuessGame/main.py
1,861
4.125
4
#Number Guessing Game Objectives: import art import random # Include an ASCII art logo. def check_greater(bot_value,player_value): if player_value == bot_value: return "Congrats, your guess is correct!" elif player_value > bot_value: return "Your prediction is higher than the actual value" elif player_...
709569e4db84902cc1a295232352a39d56a05a78
henryZe/code
/leetcode/daily/73_setZeroes_a.py
636
3.78125
4
from typing import List class Solution: # 计算 O(m * n) # 空间 O(m + n) def setZeroes(self, matrix: List[List[int]]) -> None: m, n = len(matrix), len(matrix[0]) row, col = [False] * m, [False] * n for i in range(m): for j in range(n): if not matrix[i][j]: ...
1fafea394000a7f3846e758ce70e4b24f0fff3a3
cuteboygowtham/python
/challenge code 12.py
1,216
3.984375
4
class Computer: def __init__(self, ram, processor, memory): self.ram = ram self.processor = processor self.memory = memory def getspecs(self): print("Enter the details") self.ram = input("Enter Ur ram size") self.processor = input("Enter ur processor") ...
2194f7f9e10c3a14b0d421e08fa011c90faf1b96
CharlesHowarth/Python-01
/function_multiply.py
132
3.546875
4
first = 100 second = 22 def mult(p1, p2): return p1 * p2 print("{} * {} = {}".format(first,second,mult(first,second)))
0f121ec3251aab61369e545150fb5a34a2f14fde
audhiaprilliant/Code-Chef
/DSA Learning Series/2 Linear Data Structures/1 Chef and Street Food.py
414
3.703125
4
# /usr/bin/python3.6 # source: https://www.codechef.com/LRNDSA02/problems/STFOOD # author: audhiaprilliant for _ in range(int(input())): numInput = int(input()) maxProfit = [] for _ in range(numInput): [numStore,numPeople,price] = list(map(int,input().strip().split())) profitDaily = (numPeo...
2bd1d24e6d53c6c38d86e011e39ea0f5c945cfb0
Razdeep/PythonSnippets
/AUG23/06.py
152
3.78125
4
# using sort method of list a=[9,9,8,7,6,5,5,67,8] b=['rajdeep','roy','chowdhury'] c=['9','8','7'] a.sort() print(a) b.sort() print(b) c.sort() print(c)
52d527fb6cbf13f42ecc0f3e9858f6e12c780ff6
rizkisadewa/pythoncrashcourse
/Part3/string/strechingstring.py
629
3.65625
4
# Streching The String ''' we would like to show the data in table which is contain column and line ''' data = [ ('P01','Spidol',7500,10), ('P02','Papan Tulis',8500,20), ('P03','Pencil',1500,8) ] for line in data: print('%s %s %s %s' % (line[0].ljust(5), line[1].ljust(15), st...
5a27a992e74b0d55d38088de7dda1496035d88b7
JessePullen/twitter-data-assignment
/Problem 4.py
2,115
3.6875
4
#Reads file. follow_file = open('large-data-1/follows.txt') stream_file = open('large-data-1/stream.txt') print('enter n:') #Dictionaries for data, list for sorting, int for number of users. n = int(input()) seen_tweets = {} sort_li = [] authored_tweets = {} follows_dict = {} #Find number of followed users. for line...
dfe26425291967b3be24b9f66ee68207c3953000
bobo213/learn-py
/liebiao2.py
613
3.546875
4
__author__ = 'liubo' import sys import os import time,datetime fav_movies = ["The Holy Grail","The life of Brian","The Holy grail","the life of brian","the meaning of life"] print(fav_movies[0]) print(fav_movies[1]) print("-------------------") for each_flick in fav_movies: print(each_flick) print("---------...
9b3ef0bc9ec41004d7ce0082251c6001ab23357a
manueldiazdev/BinaryTreeEvaluator
/Tree.py
1,852
4.0625
4
def main(): print("Name goes here") node1 = EvaluateTree(Node('+', Node('2.5'), Node('+', Node('7'), Node('3')))) print(node1.about()) node1.printtree() print(node1.evaluatetree()) class Node(): def __init__(self, string, left = None, right = None): self.value = string ...
90092465c01e5e65e8f50602e574d214dec20bb9
SindhuMuthiah/100daysofcode
/Replace_arr.py
166
3.53125
4
n=list(input()) a=input() b=input() for i in range(len(n)): if n[i]==a: n[i]=b elif n[i]==b: n[i]=a for i in n: print(i,end="")
a2c011b6c8b868c076316fd7368f3d6c668dea75
fulloverride/LearnPythonTheHardWay
/else
460
4.125
4
#!/usr/bin/python people = 30 cars = 40 buses = 15 if cars > people: print "we should take the cars" elif cars < people: print "we should not take care" else: print "we cant decide" if buses > cars: print "that's too many buses" elif buses < cars: print "maybe we could take the buse" else: p...
a2d51f9034e02f664d26942dca2f1110ed5f9123
BhanuPhanindra/image-classification-691
/submission/python_helper_scripts/normalize.py
640
3.984375
4
import numpy as np def normalize_features(features): ''' normalize_features(features) computes the normalized version of the features using various norms. For example if the l2 norm of the features are used, each column is of unit length. ''' #This is L1 normalization for i in ra...
0d386f16946f23d17eaa1fcf92bdba01f540fcca
jacob-brown/programming-notes-book
/programming_notes/_build/jupyter_execute/python.py
10,235
4.5
4
# Python ## Basics ### Lists Methods: * `append()` * `clear()` * `copy()` * `count()` * `extend()` * `index()` * `insert()` * `pop()` * `remove()` * `reverse()` * `sort()` demoList = ["apple", "banana", "orange", "kiwi"] print(demoList) Adding/Removing items demoList.append('cherry') print(demoList) demoList....
782d21ea362ae19cc4517a0f7d1666291d2c3cd3
Evansdava/Tweet-Generator
/scripts/Outdated/histogram.py
6,445
3.71875
4
from scripts.Outdated.dictionary_words import read_file_words from scripts.utility import time_it from random import randint @time_it def histogram_dict(text): """Read a text and return a dictionary histogram of its words""" hist = {} for word in text: word = word.lower() if word not in hi...
6bf3f135af784927de6c8b529055851515ec1578
ATLS1300/pc02-graffiti-section11-Snoobers
/PC02_Graffiti.py
5,074
4
4
#!/usr/bin/env python # coding: utf-8 ''' Turtle starter code ATLS 1300 Author: Dr. Z Author: Seliskar May 29, 2020 ''' import turtle #import the library of commands that you'd like to use turtle.colormode(255) # Create a panel to draw on. panel = turtle.Screen() w = 750 # width of panel h = 750 # height of panel ...
e4c9f760f0d8b95cb3cce76685c126f217aaa62f
IZOBRETATEL777/Python-labs
/Lesson-8/number_of_terms.py
435
3.828125
4
def numberOfTerms(n, reduction=1): if n == 0: return 1 res = 0 while reduction <= n: res += numberOfTerms(n - reduction, reduction) reduction += 1 return res while True: n = int(input('Enter a natural number: ')) if n <= 0: print('Try again') else: b...
144f13be1d51cc3de7d51ca17c2010692d8351b4
jcheng121/pythonExercise
/chp6StrExer.py
572
3.84375
4
#! /usr/bin/python data = " X-DSPAM-Confidence: 0.8475 " data = data.strip() sPos = data.find(' ') test = data[sPos+1:] test = test.strip() test = float(test) print test print type(test) # exercise 6.1 def traverseStrBack (data): index = len(data) - 1 while index > 0 : print data[index] index ...
9fd3cb00b131883dc3896831a5113e2e7e022965
crucis-onishi/tk_practice
/entry.py
2,558
3.90625
4
import tkinter as tk # tk.Frameを継承したApplicationクラスを作成 class Application(tk.Frame): def __init__(self, master=None): super().__init__(master) # ウィンドウの設定 self.master.title("ウィンドウのタイトル") # 実行内容 self.pack() self.create_widget1() # create_widget1メソッド...
238c0a27ee1dce2626ddfc937f6b44eb95b42924
TheKinshu/100-Days-Python
/Day24/snake.py
1,485
3.765625
4
from turtle import Turtle, forward, up STARTING_POS = [(0,0), (-20, 0), (-40, 0)] # Speed MOVE_DIS = 20 # Controls UP = 90 DOWN = 270 LEFT = 180 RIGHT = 0 class Snake(): def __init__(self) -> None: self.snake = [] self.create_snake() self.head = self.snake[0] def create_snake(self)...
bb4e7f71e5260ac6a5ac7e668c60760b82d6e7e2
nfarnan/cs1520_examples
/recitation_exercises/03_python.py
2,371
4.28125
4
''' Your task for this exercise is to complete the code for the class below. You'll start by reading the file '04_graph.txt' and storing it as a dict, you can also lookup what a defaultdict is and use that instead. A line in the '04_graph.txt' represents a friends relation. For example, the line a;d in the tx...
dee4b07cae8dfef43a41cb2c1036b24cd118da11
kahramaneron/alistirmalar_III
/stupid_sort.py
647
3.8125
4
def stupidSort(dizi): n = len(dizi) degisim = True #dizinin elemanlari arasinda degisim olup olmadigini kontrol etmek icin boolean deger dönülür while(degisim==True): degisim=False for i in range(0,n-1): if dizi[i] > dizi[i+1]: #büyük olan sayi her seferi...
900f283eb2abd6a75125961f3a78e680f4e2282f
Walid-Ahmed/pythonExamples
/pythonDataStructAlgorithms/sortingFunctions.py
1,796
3.984375
4
def bubble_sort(a_list): for pass_num in range(len(a_list) - 1, 0, -1): for i in range(pass_num): if a_list[i] > a_list[i + 1]: temp = a_list[i] a_list[i] = a_list[i + 1] a_list[i + 1] = temp a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] bu...
dc5dd22bad8306420820d5a7f93c123289b47166
mingyueye6/Python_senior
/chapter05/bisect_test.py
284
3.515625
4
# coding: utf-8 # 用来处理已排序的序列,用来维持已排序的序列 import bisect inter_list = [] bisect.insort(inter_list, 3) bisect.insort(inter_list, 2) bisect.insort(inter_list, 1) bisect.insort(inter_list, 4) print(inter_list) print(bisect.bisect(inter_list, 3))
063b91fa2514f3cacb8679fed3738bd846b8b766
lucasvittal2/Yathezz
/jogador.py
3,070
3.765625
4
from random import * from InstanciaJogo import * from partida import * __all__ = ["lanca_dados","identificaResultado"] #lança dados 1 vez def aux_dados(numDados): dados=[0]*numDados i=0 a=0 while(i< numDados): a=randint(1,6) dados[i]=a i=i+1 return dados #funçao que pega ...
297c6d8aa5818a4e1a56ee531bc608c5cdb83c37
rgsriram/Algorithms
/Others/vowels.py
748
3.828125
4
""" Reverse vowles a e i o u """ def is_vowel(c): return c in ('a', 'e', 'i', 'o', 'u') def reverse_vowles(str): str = list(str) i = 0 j = len(str) - 1 # apple -> eppla while i < j: i_is_vowel = is_vowel(str[i]) j_is_vowel = is_vowel(str[j]) if i_is_vowel and j_i...
5f055a719b92388dfc7a39749f3b324bb4957e8a
jeffreybyrne/python_fundamentals1
/exercise3.py
2,258
4.3125
4
#Copying & starting with a large part of the exercise we walked through with Natalie during today's lesson, I'll comment #it all out and just use it as reference # print("What's your name?") # user_name = input() # print("Hi {}!".format(user_name)) # # print("What year were you born?") # user_birth_year = input() # use...
45075ec4acc1e59e7116ed17ee2f2255c038f717
ghicheon/tensorflow
/a.py
95,554
3.875
4
./1_Introduction/basic_eager_api.py ''' Basic introduction to TensorFlow's Eager API. Author: Aymeric Damien Project: https://github.com/aymericdamien/TensorFlow-Examples/ What is Eager API? " Eager execution is an imperative, define-by-run interface where operations are executed immediately as they are called from P...
b1d74387294003803ada74812955f21e3ef35e2d
anishghimire603/Insight-Workshop-Academy
/45.py
98
3.78125
4
vowels = ('a', 'e', 'i', 'o', 'i', 'u') index = vowels.index('i') print('The index of e:', index)
e118d62657f6b7df0e67a695be716067da51b2c1
kimsutto/AlgorithmStudy
/code/BOJ/no.2580/no.2580_이동건.py
1,178
3.59375
4
import sys r = sys.stdin.readline # 가로 체크 def horizontal(x, val): if val in sudoku[x]: return False return True # 세로 체크 def vertical(y, val): for i in range(9): if val == sudoku[i][y]: return False return True # 3x3 체크 def bythree(x, y, val): nx = x//3 * 3 ny = y//...
e8ae1cab23e5ead653d3f399632cf63082a5242b
JamesdeLisle/5th-Ed-Char-Tracker
/source/dialogue.py
5,592
3.515625
4
from display import * def dispSingleList(statement,options): indentation = 3 stdscr = initialiseDisplay() stdscr.addstr(1,indentation,statement) stdscr.refresh() for tik in range(len(options)): stdscr.addstr(3+tik,indentation,'%d) %s' % (tik+1,options[tik])) stdscr.r...
a452abd42d3386f367975c01d9174e357425bf0b
TheKatherin/ThinkPython
/chapter6/ex6_3_p72.py
397
4.0625
4
def first(word): return word[0] def last(word): return word[-1] def middle(word): return word[1: -1] word = input('Want to see if it is a palindrome?\n') def is_palindrome(word): if len(word) <= 2 and first(word) == last(word): print('True') elif first(word) == last(word): is_pa...