blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
0d17b4072ba18f40dd38734748c59b9770737d68
debu999/Python_Notes
/closure_decorators/local_functions.py
3,021
3.734375
4
store = [] def sort_by_last_letter(strings): def last_letter(s): return s[-1] store.append(last_letter) print(last_letter) return sorted(strings, key = last_letter, reverse=True) print(sort_by_last_letter(["Debabrata", "Priyabrata", "Ramesh", "Devendra", "Augustine", "Boominathan"])) #Closur...
d1a177814b999f4e4b17055daeb5446dd9115f51
someOne404/Python
/pre-exam3/11.27_high_scores_append.py
440
3.59375
4
scores = [] with open('scores.csv', 'r') as f: for line in f: n, s = line.strip().split(',') if int(s) > 0: scores.append([int(s), n]) scores.sort() scores.reverse() for pair in scores: s, n = pair print(n, 'got', s) name = input('Who are you? ') score = input('What was your sco...
551d1d6e4e312cbea6630fc2530f5e5ddf502a8b
SaumLucky/python
/1.19.py
248
4.09375
4
time_gone = int(input("enter the time gone ")) hour = (time_gone % (60 * 60 * 24) // 3600 ) minutes = time_gone % (60 * 60) // 60 seconds = time_gone % 10 print(hour // 10,hour % 10, ":", minutes // 10,minutes % 10, ":", seconds // 10,seconds % 10)
ae4b57bb952ce0e54708cebc2a8333a005224e51
mukulsingh94868/ML-project
/mukki.py
474
4.3125
4
#!/usr/bin/python3 import matplotlib.pyplot as plt # only loading python ori lib x=[2,3] x1=[4,3,8] y=[9,5] y1=[2,9,7] plt.xlabel("time") plt.ylabel("speed") plt.plot(x,y,label="water") # thus will draw a straight line plt.plot(x1,y1,label="sand") # thuis will draw a straight line plt.grid(color='green') # to ...
3435584d0374723a3f365232e3bb461eff505a70
Avador-77/python-programs
/ThinkPythonBookSolutions/5-10checking usernames.py
421
3.671875
4
current_users = ['RAJat','ANMOL','bajaj','tekchand','mohit', 'shubam','pankaj'] new_users = ['Rajat','Anmol','bajaj','sathiya','nilofar'] Cu_lower = [user.lower() for user in current_users] for username in new_users: if username.lower() in Cu_lower: print("Sorry, the name " + username + ' has been taken....
b2b52bb5b71c8d5ffa77ef1c0c2e40c7e6aa7269
Simthem/algos_data_structures
/algorithms/implement_strstr.py
264
3.65625
4
def implement_str(haystack, needle): if (not haystack and not needle) or not needle: return 0; for i in range(len(haystack)): cur = haystack[i:i + len(needle)]; if cur == needle[0:len(needle)]: return i; return -1;
0a3880862e092ea689ed321bfe9b7e39b011f241
joaoluizn/exercism
/python/core/hamming/hamming.py
224
3.515625
4
def distance(strand_a :str, strand_b :str) -> int: if len(strand_a) != len(strand_b): raise ValueError("Strand Lenths doesn't match.") return len([(s1, s2) for s1, s2 in zip(strand_a, strand_b) if s1 != s2])
8163d724b812afd2702e2337f27d989c7a03190d
Lokitosi/Python-UD
/Programa graficador de poligonos.py
624
3.828125
4
import turtle pipo = turtle.Turtle() cerrar = 0 def figura(): lados = turtle.numinput("Lados", "Ingrese cuantos lados tendra la figura:") tamaño = turtle.numinput("Tamaño", "Ingrese el tamaño de la figura:") relleno = turtle.textinput("relleno", "Desea rellenar la figura") pipo.clear() ...
10e81551185865e7f1e773a17a5cb75874a615ba
darioss/estudos
/Python/divisao_inteira.py
258
3.90625
4
def main(): # escreva o seu programa num1 = int(input("Digite o valor de n (n > 0): ")) num2 = int(input("Digite o valor de d (0<=d<=9): ")) resultado = num1//num2 print("O Digito %d ocorre %d vezes em %d" %(num2, resultado, num1)) main()
b400fa8072e376108d86c8f4782ceb14e4348978
AlexKaracaoglu/Cryptography
/PS1/AKaracaogluHW1.py
8,386
3.609375
4
import conversions import string from timeit import default_timer as timer # NAME: ALEX KARACAOGLU # Code for number 2 (Some pieces may be used later on as well) # The cipher text was given in hex, I will convert them to ascii and use them ciphertext1_in_b64 = "EjctKjswcH5+GjF+JzErfik/MCp+KjF+NTAxKX4/fi07PS...
823dc05bfc37e20f35c801f26ab0457ab99929e6
eedriss67/User-Log-in-Project
/user_log-in project.py
851
4
4
# This is a simple project that takes user's log-in information and validates it. import time name = input("Create a log-in name: ") password = input("Create a password: ") user_name = input("Please enter your name to log-in: ") user_password = input("Please enter your password to log-in: ") if user_name ...
67cedaff99a04f30ab73b174cc41e6135765105c
idalyli/pildoraspython
/funcioneslambda/practica_map.py
684
3.546875
4
class Empleado: def __init__(self,nombre,cargo,salario): self.nombre=nombre self.cargo=cargo self.salario=salario def __str__(self): return "{}que trabaja como {} tiene un salario de $ {}".format(self.nombre,self.cargo,self.salario) lista_empleados=[ Empleado("Juan","Directo...
9d54965d4ed2fb1a6b2f2d43414897d8893179a3
uilic/socialflask
/people.py
2,016
3.546875
4
class Human: """Class human with the atributes given in the data.json file, and also with one extra atribute, string ID for easier work with picture urls""" def __init__(self, ident, firstName, surName, age, gender, friendsId): self.ident = ident self.firstName = firstName self...
5afc30f13063bd0bf4c86e105ba1d09896d14cca
asierblaz/PythonProjects
/Listak/Listak11.py
216
3.71875
4
''' 17/12/2020 Asier Blazquez Write a Python program to find the index of an item in a specified list ''' import random list =["a","e","i","o","u"] aleatorioa =int( random.randrange(0, len(list)-1)) print(list[aleatorioa])
9e35c703baaaa26a852852f611ee5a14afd4af8a
mikkokotila/game-theory-sim
/gt.py
4,911
4.09375
4
#!/usr/bin/python import time import random # starting turn and per turn cost for players turn = 0 tax_rate = 0.2 cost_of_living = 0.3 players = 2 service_cost = 0.01101 minimum = 0.1 gdp = 1 demand = 1 inflation = 0.01 # productivity and resource settings productivity = 1 current_account = 100 motivation_adjustme...
f0489bf500a492b8499e77fdaedcc4b5dc55bf6a
eli-front/excessive-tic-tac-toe
/python/ttt.py
2,680
3.890625
4
# Copyright (c) 2020 Eli B. Front. All rights reserved. from os import system, name board = [[' ', ' ', ' '],[' ', ' ', ' '],[' ', ' ', ' ']] currentPlayer = 'x' # Prints the current board and clears the previous board def printBoard(): # for windows if name == 'nt': _ = system('cls') # for mac...
e1db4276b50a0eb813d728182e6a79e68b87bcb4
wanghan79/2020_Master_Python
/2019102960李婧怡/第三次作业:randomFloatStr.py
1,263
3.75
4
import random def randomFloat(start, end): #1.随机生成1000个[0,100]范围内的浮点随机数,取出[20,50]之间的数字,存放在set集合中 set_random_float = set() for i in range(1000): randomFloat = random.uniform(start, end) #生成随机浮点数 if randomFloat>= 20 and randomFloat<= 50: print('小于20并大于...
835a31c68bb82734fb407a18dc3b5df79e9c6f3d
Aasthaengg/IBMdataset
/Python_codes/p02260/s841811880.py
748
3.84375
4
def selection_sort(alist): """Sort alist by selection sort. Returns the sorted list and number of swap operation. >>> selection_sort([5, 6, 4, 2, 1, 3]) ([1, 2, 3, 4, 5, 6], 4) """ size = len(alist) c = 0 for i in range(size): mini = i for j in range(i, size): ...
e98cbe4360f5d601ae362b3491cd236ec0ef7a0c
LinaMeddeb/GuessTheNumber
/GuessTheNumber.py
916
3.9375
4
# Guess my nbr from random import randint nbr_essays_max = 5 nbr_essays = 1 max_random = 20 my_nbr = randint(1,max_random) # number chosen by the PC your_nbr = 0 # Number proposed by the player print("I chose a number between 1 and",max_random) print("It's up to you to guess it in ",nbr_essays_max,"attempts at most!") ...
46f766b2d8fed1a909a6086b69e4200bdbcf58aa
Hilldrupca/LeetCode
/python/Monthly/Oct2020/sortlist.py
5,766
4.25
4
from typing import Tuple class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def _path(self): '''Helper method to ensure correct next values''' res = [] node = self while node: res.append(node.val) ...
155f68308b2aee9f02de512c794cd134b1db9b9a
Allen-Maharjan/Sudoku_Queens
/backupqueen.py
1,391
3.578125
4
initial_grid = [[0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0]] counter = 0 def main(): #let us consider four queens which should not attack each other counter1 = 0 q = [1,1,1,1] print(initial_grid) #putting the queen in the initial grid ...
eb9617eb4c9a77ef08b7176f8da7cd906c29000c
nladino215/day6-nladino215
/problemSetDay6.py
307
4.09375
4
# File name: problemSetDay6.py num = 1 n = int(input("write a number")) while num <= n: if num % 2 == 0: print("# is even") num += 1 if num % 2 != 0: print("# is odd") num += 1 t = "*" print(t) while t != "****": if t != "****": t += "*" print(t)
b8ef08df95ed33b673247a79f88845a57eb65c26
HiddenEvent/PYthon_Start
/workspace/.vscode/Day03/Test01.py
446
3.734375
4
198*256 print("{}*{}={}".format(198,256,198*256)) #문자열과 정수 출력 print("%s : %d"%("나이",20)) print("{} : {}".format("나이", 20)) #실수 출력 -- 파이썬에서는 서식문자를 사용할 떄만 출력시 소수점 6번쨰 자리까지 기본출력이 된다. print(123.567) print("%f"%(123.567)) print("%f , %.2f"%(123.567, 123.567)) print("{:f}".format(123.567)) print("{:f} , {:.2f}".f...
58027840c7367d8695fb96a13d1f3b3fb6c6e8e1
pashkewi41/SpecialistPython2_v2
/Module3/practice/03_task_Fraction_part1.py
1,813
3.9375
4
# Задание "Простые дроби" class Fraction: def __init__(self, fraction_str): # Дробь в конструктор передается в виде строки # А мы храним дробь в виде self.numerator = ... # числителя self.denominator = ... # знаменатель # целую часть перебрасываем в числитель # минус, есл...
889c1490773dc07bd1abd1f33462ca696334f809
sebnorth/flask-python-coursera
/app/static/Memory.py
2,913
3.890625
4
# Mini-project 5 for An Introduction to Interactive Programming in Python class # based on the template from: http://www.codeskulptor.org/#examples-memory_template.py import simplegui import random memory_deck = range(8) + range(8) print memory_deck exposed = [False]*8 + [False]*8 print exposed board_height = 100 b...
93ca60fa6c722bbc59f89c4e37da46239e3ed962
wellington-ishimaru/IFSP-Funcoes
/questao3.py
281
4.15625
4
#-*- coding: UTF-8 -*- def soma (num1, num2, num3): return num1 + num2 + num3 numeros = [] for i in range(0, 3): numeros.append(float(input(f"Digite o numero {i + 1} de 3: "))) print(f'A soma dos 3 numeros e igual: {soma(numeros[0], numeros[1], numeros[2])}')
49f42081ffb84f868943291bb51f0642cc23556f
muttakin-ahmed/testPythonRepo
/fibonacciSeqGen.py
379
3.828125
4
def fib(n): a=1 b=1 fib_seq = [] fib_seq.append(a) fib_seq.append(b) for i in range(n): a,b = b,a+b fib_seq.append(b) return fib_seq[:n] while True: try: num = int(input("Please enter a number: ")) except: print("Invalid Input. Please try again.") ...
fa1c5c648fd562f636721c0649ddbe2217597363
dongyeon94/basic-exercise-Python
/tkinter_game/maintable.py
2,176
3.53125
4
## 수정 해야 될듯 from imagebtn import * from tkinter import * from random import * import time class Maintable(Frame): n = 0 selected_image = 0 def __init__(self, master, picture, alphabet, width): super(Maintable, self).__init__() self.image_number_list = [] # 셔플된 이미지의 번호를 저장하기 위한 리스트. 16개 ...
444d6aa41895fcc6797d84596fa39a4f7d16c288
avnit/https---github.com-avnit-ContractWork
/Class1/FirstPython.py
298
4
4
print('Hello World Python!') #first code n=5 while(n>0): print(n) n = n -1 print('done') # second code n=10.0 r=10.0 n = int(n) print(type(r)) r = int(r) print(type(r)) while(n>0): while(r>0): z = n**r print(n,"*",r,"=",z) r=r-1 n=n-1 # third code sample
3e4f82d16820d3904415ce7ce0a122d4796764a2
Auphie/univHomework
/semister1/hw_041a.py
359
3.796875
4
def numDecod(string): res = 0 if string == '' or string[0] == '0': return res if len(string) <= 2 and int(string)<=26: res += 1 if 1 <= int(string[0]) <=26: res += numDecod(string[1:]) if 1 <= int(string[0:2]) <=26: res += numDecod(string[2:]) return res a ='...
ad60da822b91373a570d468f016d83d171386ea7
bettyYHchen/Model-the-Bicycle-Industry
/main.py
1,705
3.59375
4
from Bike_business import * import random import copy bike_list=[] for j in xrange(6): j=j+1 name='bike%s'%j cost=150.00+float(random.choice(range(400))) weight=50.00+float(random.choice(range(10))) b=Bicycle(name,weight,cost) bike_list.append(b) bike_list[0].cost=101.0 inventory={} for b in bike_list: invento...
bbfa2d1931c4e03bac83ffdff7c613fe0e63efd0
marcosviniciussd/CalcProjects
/tempo.py
425
3.75
4
segundos_str = input("Entre com o numero de segundos que deseja converter: ") total_segs = int(segundos_str) horas = 0; minutos = 0 segundos_restantes = 0 segundos_restantes_final = 0 horas = total_segs // 3600 segundos_restantes = total_segs % 3600 minutos = segundos_restantes // 60 segundos_restantes_final = segun...
a3ba38f479a3fe4eb0aaefdce987e2237e191755
sourcery-ai-bot/Python-Curso-em-Video
/python_exercicios/desafio083.py
856
4.21875
4
# Crie um programa onde o usuário digite uma expressão qualquer que use parênteses. # Seu aplicativo deverá analisar se a expressão passada está com os parênteses abertos e fechados na ordem correta. while True: exp = str(input('Digite uma expressão matemática: ')) if exp.count('(') != exp.count(')'): ...
55fd0d5e3bb62c73193112e6336379950f82edbb
belsouza/backupexercises
/python/partida.py
2,643
3.90625
4
global v_user = 0 global v_comp = 0 partida_vencedor = "" n = int( input("Quantas peças? ") ) m = int( input("Limite de peças por jogada? ") ) jogada = n % (m+1) end = False vezpc = "" vezuser = "" if jogada == 0: print("Você começa!") vezuser = True ...
45c37538f3bf62d1141fa15a78bbd663598b620f
pyparsing/pyparsing
/examples/indentedGrammarExample.py
1,016
3.515625
4
# indentedGrammarExample.py # # Copyright (c) 2006,2016 Paul McGuire # # A sample of a pyparsing grammar using indentation for # grouping (like Python does). # # Updated to use indentedBlock helper method. # from pyparsing import * data = """\ def A(z): A1 B = 100 G = A2 A2 A3 B def B...
1cc32cc462131ca1a8bfe1fd336ceea804985fb9
jhylands/sle
/sle/graph.py
1,818
3.609375
4
#!/usr/bin/env python # a bar plot with errorbars import numpy as np import matplotlib.pyplot as plt import sys #get the input string and split it into X-axis labels, values, error bars input =[sys.argv[1].split('Z')] #split the X-axis labels element into an array of those labels XLabels = input[0][0].split('Y'...
902d90d4c9224a06260a5a8c516dfdfcfa2cab2f
nirvana9/py
/test/ex_02.py
95
3.546875
4
#!/usr/bin/env python s = 0 for x in range(101): s = s + x print s print sum(range(101))
00abf2e887bd0f1d4f36834045ccef65e86906ea
ari-hacks/kata-practice
/tests/python_test/phone_number.py
650
3.859375
4
import unittest from katas.python.kyu6.phone_number import create_phone_number class TestCreatePhoneNumber(unittest.TestCase): def test_create_phone_number(self): self.assertEqual(create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]), "(123) 456-7890") self.assertEqual(create_phone_number([1, 1, 1, ...
f401968a0bca6f9021f6c1fd927ce9f4b3e3151e
Arin-py07/Python-Recursion
/SumofNaturalNo.py
103
3.65625
4
#Summary n = 10 n=int(input("Enter n:")) sum=n*(n+1)//2 print("sum is",sum) #Output Enter n:sum is 55
9723792da73ae1b60454938393e409f962334b41
KazutoYunoki/programing-contest
/atcoder/abc143/c.py
246
3.640625
4
def main(): N = int(input()) S = list(input()) merge = [] sura = S[0] merge.append(sura) for i in S: if i != merge[-1]: merge.append(i) print(len(merge)) if __name__ == "__main__": main()
34748d3856c7a66ce05e3f8835b3b02e741ddd79
KloseRinz233/gobang
/tools.py
2,286
3.734375
4
def check_position(array,x,y): if(x<0 or x>14 or y<0 or y>14): return False else: return array[x][y] def check_surrounding(array,x,y,deep): for i in range(-deep,deep+1): for j in range(-deep,deep+1): if((i!=0 or j!=0) and (check_position(array,x+i,y+j)==1 or check_positio...
4b5e18f174f912f9710e729248af3245d49944af
MrHamdulay/csc3-capstone
/examples/data/Assignment_2/ptrjas005/question3.py
176
4.125
4
print("Approximation of pi: 3.142") x = eval(input("Enter the radius:\n")) area = round(x**2*3.142,3) if (area==19.637): print("Area: 19.635") else: print("Area:",area)
ca5385f438ebf6c3a585795a0cc528f81b2ef1cf
TheAlphaQuacker/second-try-at-my-quiz
/main.py
386
3.671875
4
from tkinter import * class MainScreen: def __init__ (self, master): background_color = "black" self.main_frame = Frame(master, bg = background_color, padx=100, pady=100) self.main_frame.grid() self.Heading_label = Label(self.main_frame, ) if __name__ == "__main__": root = T...
08759d17585271d4d521202a7bf08bb2b92ba443
scheidguy/ProjectE
/1-50/prob5.py
337
3.546875
4
# -*- coding: utf-8 -*- """ Created on Wed Sep 16 15:53:51 2020 @author: schei """ max_val = 20 num = 20 not_done = True while not_done: for mod in range(max_val, 1, -1): if num % mod != 0: num += 1 break elif mod == 2: not_done = False print(num) ...
a91fd2c4444d81f9677dbd38ca1bd93af1b7b06b
adh2004/Python
/Lab10/Lab10P2.py
482
4.28125
4
import length def main(): inches = 0 feet = 0 m = 0 cm = 0 miles = 0 km = 0 inches = int(input('How many inches?: ')) cm = length.inches_to_cm(inches) print('It is equivalent to ', cm , ' cm') feet = int(input('How many feet?: ')) m = length.feet_to_m(feet) print('It i...
a2faf5e7f112893f4ed86ff42dfffd7008cef0a6
jinzhe-mu/muwj
/class_python/异常.py
909
3.921875
4
##出现了异常进行异常捕获,当不知道异常时候,可以直接用except: 不加具体异常进行捕获 while True: try: num1 = int(input("输入一个除数")) num2 = int(input("输入一个被除数")) print(num1/num2) break except ZeroDivisionError: print("被除数不能为零") except ValueError: print("请输入数值型整数") except: print("输入数字异常"...
d3ca48f3a24cbd97bf60ac340112fd850f4038e2
oskomorokhov/python
/study/checkio/Home/caesar_cipher_encryptor.py
1,575
3.828125
4
#!/usr/bin/env checkio --domain=py run caesar-cipher-encryptor # https://py.checkio.org/mission/caesar-cipher-encryptor/ # This mission is the part of the set. Another one -Caesar cipher decriptor. # # Your mission is to encrypt a secret message (text only, without special chars like "!", "&", "?" etc.) using Caesar ...
6e2f8de1fec7a67963b5b7847f90e3425ce9cbfd
saikirandulla/HW05
/HW05_ex09_01.py
680
3.84375
4
#!/usr/bin/env python # HW05_ex09_01.py # Write a program that reads words.txt and prints only the # words with more than 20 characters (not counting whitespace). ############################################################################## # Imports # Body def long_words(): try: fin = open('words.txt') line =...
05a867311f8a3c72881ac5978b57847b3e1efe09
Monster-Moon/hackerrank
/baekjoon/02/9498.py
197
3.578125
4
score = int(input()) score_dic = {'A' : [90, 100], 'B': [80, 89], 'C': [70, 79], 'D': [60, 69], 'F': [0, 59]} print([i[0] for i in score_dic.items() if score >= i[1][0] and score <= i[1][1]][0])
cb06d55273dbe85bbfce046c4301478fbb9e9bb1
hcodydibble/data-structures
/src/quick_sort.py
570
4.03125
4
"""Function for implementing a quick sort algorithm.""" def quick_sort(a_list): """Quick sort algorithm.""" if isinstance(a_list, list): if len(a_list) < 2: return a_list ref_num = [a_list.pop(0)] bigger_nums = [] smaller_nums = [] for num in a_list: ...
56e8a3f3b6f91cd94a02152b42cf6f4a96a73638
nick-delgado/python
/googleapi.py
752
3.734375
4
import googlemaps from datetime import datetime #API-KEY= AIzaSyDV93OxljDchBbiBHjfjfbhpMMIyn3aYs8 gmaps = googlemaps.Client(key='AIzaSyDV93OxljDchBbiBHjfjfbhpMMIyn3aYs8') reverse_geocode_result = gmaps.reverse_geocode((35.10873, -86.11313)) #what is returned? #what can be parsed? #is it always consistent? #does ...
4f83e3c6cf695e27e17a07cfd778262aad65a718
T-Douwes-UU/NumeriekeMethoden
/Project 1/1.10.2.3_template.py
6,243
4.40625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ########################## PART 3 ########################## """ We can now make the pendulum a bit more realistic, by adding a viscous friction with air. The equation of motion of the pendulum with the addition of viscous friction become theta''(t) = -(g/L) * sin(the...
542624d0e5e0373763a9b0b886d40fc269c2925a
paulrodriguez/daily-coding-problem
/problem_137.py
1,090
4.125
4
''' Implement a bit array. A bit array is a space efficient array that holds a value of 1 or 0 at each index init(size): initialize the array with size set(i, val): updates index at i with val where val is either 1 or 0. get(i): gets the value at index i. ''' ''' time complexity: O(1) space complexity: O(1) ? (only u...
abab52e44e2653a6e81fe719c592b289ce17fae2
williamsyb/mycookbook
/algorithms/BAT-algorithms/Tree/二叉查找树-两数之和.py
1,616
4.09375
4
""" 一、题目 给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定的目标结果,则返回 true。 二、案例 输入: 5 / \ 3 6 / \ \ 2 4 7 Target = 9 输出: True(因为存在 2 + 7 = 9) 三、思路 使用中序遍历得到有序数组之后,再利用双指针对数组进行查找。 应该注意到,这一题不能用分别在左右子树两部分来处理这种思想,因为两个待求的节点可能分别在左右子树中。 """ # Definition for a binary tree...
441a7d743a3e9aae1dab54eec1750bc4517f7119
Wolemercy/monty-hall
/monty-hall.py
1,864
3.796875
4
# The Monty Hall Problem import random # Instantiating a random treasure map def single_run(): maps = ['wasteland', 'wasteland', 'wasteland'] treasure_index = random.randint(0, 2) maps[treasure_index] = 'one piece' return maps # Luffy's first choice def luffy(): luffy_first_choice = random.randin...
9aa88f0b5dc3921b398cc59305289ffabd54d14b
DavidSchmidtSBU/DavidSchmidtSBU.github.io
/Bible2.py
814
4.09375
4
# First find a bible in text form inFile = open('KJV12.TXT', 'r') MyWord = 'God' #Initialize MyWord count = 0 #Initialize count inLine = inFile.readline() #Read in a line of text while (inLine != ''): #While more lines to read lineList = inLine.split(...
e6aebf71ce7887dbc48b05a3b49a6bf365c5677e
BreakZhu/py_recommend_demo
/sort/insertSort.py
1,214
4.03125
4
#!/usr/bin/env python # coding:utf-8 """ 插入排序: 对于一个n个数的数列: 拿出第二个数,跟第一个比较,如果第二个大,第二个就放在第一个后面,否则放在第一个前面,这样前两个数就是正确顺序了 拿出第三个数,跟第二个数比较,如果比第二个数小,就放在第二个数前面,再跟第一个数比,比第一个小就放在第一个前面,这样前三个数就是正确顺序 .... 拿出最后一个数,跟之前的正确顺序进行比较,插入到合适的位置当中。 可以理解成: 每次拿到一个数,他前面都是一个有序的数列,然后,找到我何时的位置,我插入进去 最坏时间复杂度: O(n^2) 最优...
cd22553a918a290415e26406e8f8e0ccb306d066
sai-kumar-peddireddy/PythonLearnigTrack
/Tuples/Tuples.py
1,581
4.21875
4
""" Tue Jul 24 04:49:08 IST 2018 source : https://www.geeksforgeeks.org/tuples-in-python/ Tuples Tuples are similar to lists. repetition, nesting, indexing is similar to list Tuples are immutable lists are mutable Tuples are represented in () """ t1 = () # empty tupple print(t1, "\tlen(t1)", len(t1)) t = ...
f73e8fbd52485cdbfb4e189293cc795f47c99c84
rudolphlogin/Python_training
/class and modules/write_file_txt.py
1,786
3.78125
4
'''Demonstrate writing text to a file''' from io import UnsupportedOperation print('Default Windows 10 encoding "cp1252".') with open('C:\\Users\\nbg4kdv\\Documents\\UPS\CDP\\Python\\written.txt',mode='w') as out_file: out_file.write('This is the first line of text.\n') with open('C:\\Users\\nbg4kdv\\Docum...
7ed5687461706e83a8a8bd4fbf4a977e3af7705a
finalshake/machine-learning
/python/thread.py
982
3.625
4
import threading, time str = '' counter = 0 lock = threading.Lock() def do_count(): global counter print('%s counting to %d' %(threading.current_thread().name, counter)) counter += 1 time.sleep(1) def count(): global counter global str switcher = False while True: if str == 's...
e257c939df135cf613423568d384504b3a30bb79
paulacaicedo/TallerAlgoritmos
/ejercicio20.py
317
3.84375
4
#EJERCICIO 20 numero=int(input("Introduzca un diigto: ")) numero_nn=numero*11 numero_nnn=numero*111 resultado=numero+numero_nn+numero_nnn print("El valor digitado es: ",numero) print("El valor digitado nn: ",numero_nn) print("El valor digitado nnn: ",numero_nnn) print("El resultado de la suma es: ",resultado)
2a8c23a5f3c59a1e61e3582212f51b9f5761605a
jpmacveigh/Particule_atmos
/ew.py
559
3.5625
4
def ew (temperature): """ Calcul de la pression de vapeur saturante (hPa) en fonction de la température (°C) par la formule de Tetens formule de Tetens: ew=6.107*10**(7.5*temperature/(temperature+237.3)) Permet de calculer, par définition de sa température du point de rosée Td, la...
101baddd04f942e5937f4d3df88ca44abc32b4bd
shaked-nesher/mat1
/equations.py
1,547
3.609375
4
# -*- coding: utf-8 -*- """ Created on Mon Mar 15 14:59:31 2021 @author: shaked nesher """ def pow1(z, num): sumpow = 1 for i in range(num): sumpow *= z return float(sumpow) def factorial(num): sumfactorial = 1 for i in range(1, num + 1): sumfactorial *= i return float(sumfac...
3c63f5f208d7e5a8075ed4bc4ca1bdc3c8ddb3af
152midnite/Vision
/verification/metrics.py
1,526
3.609375
4
answers = {} with open('./results','r') as file1: lines = file1.readlines() for line in lines: print(line) key, value = line.split(' ') key, value = key[:],value[:-1] if key in answers: if value in answers[key]: continue else: ...
48d709b8d433781039928bc7e31677aaabeca49c
girishgupta211/algorithms
/string/rearrange_sentence.py
721
3.765625
4
def rearrangeTheSentence(sentence): dot_exists = False if sentence[-1] == ".": sentence = sentence[:-1] dot_exists = True arr = sentence.split(' ') n = len(arr) arr[0] = arr[0].lower() for i in range(1, n): word = arr[i] j = i - 1 while j >= 0 and len(wor...
874a39ff6f49b7cba3d279f1d311a2b22479b555
wenjunli-0/Simulation-Methods-for-Stochastic-Systems
/codes/project2_Q1.py
2,072
3.515625
4
# Question 1 import numpy as np import matplotlib.pyplot as plt # part (a) N = 1000 # switch N among: 100, 500, 1000 samples = np.random.uniform(-3, 2, N) counts, bins, ignored = plt.hist(samples, edgecolor='black', alpha=0.75) plt.figure(1) plt.title("Histogram of {} Uniformly Distributed Samples".format(N)) pl...
be6c47fc775d7b01e5ea4670f1d69ae9f963eb50
Ciuel/Python-Grupo12
/Materia/Practicas/Practica2/Practica2E10.py
1,309
3.890625
4
''' 10. Escriba un programa que solicite por teclado una palabra y calcule el valor de la misma dada la siguiente tabla de valores del juego Scrabble: Letra valor A, E, I, O, U, L, N, R, S, T 1 D, G 2 B, C, M, P 3 F, H, V, W, Y 4 K 5 J, X 8 Q, Z 10 *Tenga en cuenta qué estructura elige para guardar estos valores en P...
b738662ddfd1947917431ef6eec224e4e4292cef
davidbosss/py_notes
/mdp_example.py
1,178
3.625
4
# Markov Decision Process Example # Author: Christina Dimitriadou (christina.delta.k@gmail.com) # Date: 20/06/2021 # Import Libraries import sys sys.setrecursionlimit(1000) # create the model: class TestMDP(object): def __init__(self, N): self.N = N # N is the number of blocks def initialState(self):...
e1c98ed2fa37f6a4cdeee2034fd74652974175fa
gebijiaxiaowang/leetcode
/offer/30.py
1,233
3.8125
4
#!/usr/bin/python3.7 # -*- coding: utf-8 -*- # @Time : 2020/9/4 20:09 # @Author : dly # @File : 30.py # @Desc: class MinStack(object): def __init__(self): """ initialize your data structure here. """ self.help_list = [] self.stack = [] def push(self, x): ...
cb33874f5385162e97a5a5a4990020d9b54bbda5
learnerofmuses/slotMachine
/csci152Spring2014/feb6p1.py
593
4.03125
4
#Design a program that asks the user to enter a series #of 20 numbers. The program should store the numbers in a list #and then display the following data: #the lowest number in the list #the highest number in the list #the total of the number in the list #the average of the numbers in the list import random def...
1409080ecb2c3189785c75ef5eed8743edd08b6b
rfc8367/R1
/L2/Bonus 1.py
301
3.84375
4
x = float(input("Введите число: ")) tpl = (10, 20, 30, 40, 50, 60, 70, 80, 90, 100) if x in tpl or abs(x) in tpl: print("Число" , x, "присутствует среди элементов") else: print("Число" , x, "отсутствует среди элементов")
2577f1e2a52fec47a4f603f2fd496fa33ff07dfa
csshlok/Prac-file
/Q2.py
106
3.96875
4
celsius = float(input("Enter Celcius: ")) fahrenheit = (9/5)*celsius + 32 print("Fahrenheit ",fahrenheit)
e28787446c9911c2c5e3c9ac8b2d1a400d047a23
frankieliu/problems
/leetcode/python/680/original/680.valid-palindrome-ii.0.py
787
3.609375
4
# # @lc app=leetcode id=680 lang=python3 # # [680] Valid Palindrome II # # https://leetcode.com/problems/valid-palindrome-ii/description/ # # algorithms # Easy (33.56%) # Total Accepted: 59.3K # Total Submissions: 176.7K # Testcase Example: '"aba"' # # # Given a non-empty string s, you may delete at most one chara...
2da48199ed0005985339debfe46578494b0487c7
sidmaskey13/assignment_3
/Ac.py
573
3.796875
4
#Quick sort def partition(x, low, high): i = (low - 1) pivot = x[high] for j in range(low, high): if x[j] <= pivot: i = i + 1 x[i], x[j] = x[j], x[i] x[i + 1], x[high] = x[high], x[i + 1] return (i + 1) def quickSort(x, low, high): if low < high: ...
0bfd1019d812ff07605422be6d326f9d9baa0dbc
tommyli3318/Zot-Calendar
/flask-backend/course.py
2,251
3.5
4
from courseTask import CourseTask class Course: """contains all the information for a specific course""" def __init__(self, course_name: str, category_weights: dict) -> None: self.course_name = course_name self.category_weights = category_weights # self.cat_scores = {n:(0,0) for n in self.category_weights} # ...
1dd1477b9c7b9b48962fb948399bdb5ff82dd587
joshuasearle/ds-and-algs
/adts/heaps/heap.py
1,519
3.90625
4
class AbstractHeap(object): """ Stores the min item at root """ def __init__(self): self.array = [] self.length = 0 def __len__(self): return len(self.array) def parent_index(self, i): return (i - 1) // 2 def left_index(self, i): return 2 * i + 1 ...
a68b60d20055522231a77787454a3176af012b2c
incessantmeraki/probabilities
/probability_one.py
557
3.5
4
import numpy as np import matplotlib.pyplot as plt import seaborn as sns result = [] def throw_coin (number_of_samples, sample_sizes): for i in range(number_of_samples): trial = np.random.choice(['H','T'], size = sample_sizes) result.append(np.mean(trial == 'H')) return result sample_sizes = np...
717d424ced232d6ad69c446926b6b4599154d57c
ClockWorks001/pyworks
/hello12.py
315
3.71875
4
# coding: UTF-8 # 辞書 key value sales = {"taniguchi":200, "fukoji":300, "dotinstall":500} print(sales) print(sales["taniguchi"]) sales["fukoji"] = 800 print(sales) # in print("taniguchi" in sales) #True # keys, values, items print(sales.keys()) print(sales.values()) print(sales.items()) print(len(sales))
a53876680961d15e7fc19a323e2b5319cbb5b173
simon090/cs50
/credit.py
1,195
3.90625
4
import sys if len(sys.argv) == 2: card_num = sys.argv[1] else: card_num = int(input("Enter card number: ")) print(card_num) def valid_card_checker(number): doubles_list = [] doubles_list_singles = [] singles_list = [] for i,j in enumerate(reversed((str(number)))): if i%2!=0: ...
f85319f68d3998192f6ddad164018827ac727689
kr-aashish/Customer-segmentation-using-Hierarchical-Clustering
/Project.py
1,512
3.53125
4
#importing necessary libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt #importing datasets Dataset = pd.read_csv('Customers.csv') X = Dataset.iloc[:, [3,4]].values #.values will give array rather df #Using dendogram to find optimal number of clusters import scipy.cluster.hier...
d4345c54dbe811072bfd1366ed011c012dede49b
NamburiSrinath/Artificial-Intelligence
/gradientdescent/gradientdescent.py
1,064
3.84375
4
import numpy as np import matplotlib.pyplot as plt function = lambda x: (x ** 3)-(3 *(x ** 2))+7 #Get 1000 evenly spaced numbers between -1 and 3 (arbitratil chosen to ensure steep curve) x = np.linspace(-1,3,500) #Plot the curve plt.plot(x, function(x)) plt.show() def deriv(x): x_deriv = 3* (x**2) - (6 * (x)) re...
d2c05b2602baad40d2fb3058d73ee6acc9c235b3
ChinYikMing/pyscript
/file.py
186
3.734375
4
#!/usr/bin/python filename = "text.txt" fd = open(filename, "w") fd.write("Hello") fd.write("World") fd.close() fd = open(filename, "r") for line in fd: print(line) fd.close()
73f95dd0630e0ce609ab3540197b1e97103b99f4
Nico-Duduf/Formation_Python
/Exercices/digit.py
208
3.734375
4
test = 7 numCar = 3 def numero(num,nbreCaracteres): chaineNum = str(num) while len(chaineNum) < nbreCaracteres: chaineNum = "0" + chaineNum return chaineNum print(numero(test,numCar))
2996dc55bb01f036f0df13c8449ee823020c2c58
Krishna9331/python
/chapter11/ex11.py
282
4.03125
4
# end='' tell that go to next line without putting new line print("How old are you?", end=' ') age = input() print("How tall are you?", end=' ') height=input() print("How much do you weight?", end=' ') weight=input() print(f"So you're {age} old, {height} tall and {weight} heavy.")
c71752902154de4d67f501dd5a2fd5bb660ecf01
suziW/myLeetCode
/77.py
537
3.78125
4
from typing import List class Solution: def combine(self, n: int, k: int) -> List[List[int]]: r = [] def backtrack(combination, n, k): if k == 0: r.append(combination[:]) return for i in range(k, n+1): combination.append(i) ...
398be0416eb43110e7927fe952971f4b5d6711b4
Icode4passion/practicepythonprogams
/word_count.py
861
4.125
4
# # word_list = ["red","yellow","green","red","blue","green","orange"] # # unique_word = [] # # for word in word_list: # # if word not in unique_word: # # unique_word+=[word] # # word_frequency = [] # # for word in unique_word: # # word_frequency += [float(word_list.count(word))/len(word_list)] # # for i in rang...
a78b142329849409a342d196ca855ee2b11fb521
tartofour/python-IESN-1BQ1-TIR
/exercices/serie1/ex10.py
525
3.875
4
#!/usr/bin/env python3 total_secondes = int(input("Entrez un nombre de secondes : ")) nb_semaines = total_secondes // 604800 nb_jours = (total_secondes % 604800) // 86400 nb_heures = ((total_secondes % 604800) % 86400) // 3600 nb_minutes = (((total_secondes % 604800) % 86400) % 3600) // 60 nb_secondes = ((((total_s...
6e25daed7c0441da127781f8be1d1ef31f95bf97
unknown090105/algorithm
/grokking/Ch09/longest_common_substring.py
790
3.921875
4
def longest_common_substring(word_a, word_b): # 2d array construction cols = len(word_a) rows = len(word_b) table = [] for i in range(cols): col = [] for j in range(rows): col.append(0) # initialization with 0 table.append(col) # maximum distance calculation...
a3100f10719f3ea6118720b005558dc0dae79fb6
BOSONCODE/Python-Tutorial
/PythonBasic/面向对象/class.py
2,239
4.40625
4
''' OOP: object-oriented programming 面向对象是一种方法, 这个说起来是软件工程里面的长篇大论 这里粗略简单地来说的话就是 物以类聚 比如说 芒果、苹果、香蕉 这些都是一个一个的对象 这些可以归为一类就是水果 然后水果之间又有一些关系, 比如说长在树上的可以分为一类, 长在地上的分为一类, 那么 这些又是继承于水果这一个类 水果类专业术语叫做基类 生长环境类又叫做 派生类 多态就是基类的不同行为 ''' #私有变量不可以直接访问只能由当前类访问 #protected 派生类可以访问 但是不可以直接由对象访问, 对象不可以直接访问 #public 基类、派生类和对象都可以直接访问 class B...
30f96300274d383c4934fa60baf22dd2afbd1dd9
santhosh-kumar/AlgorithmsAndDataStructures
/python/problems/array/find_min_in_sorted_rotated_array.py
1,425
4
4
""" Find Min In Sorted Rotated Array Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). Find the minimum element. You may assume no duplicate exists in the array. """ from common.problem import Problem class FindMinInSortedRotatedArray(Probl...
db1fd179ca6079c70b43ef1f1e7981a254f0cf35
JerinPaulS/Python-Programs
/PartitionList.py
1,489
4.03125
4
''' 86. Partition List Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions. Example 1: Input: head = [1,4,3,2,5,2], x = 3 Output: [1,2,2...
8cfab1be8340b252162100aadc31ec83d82db6b1
Chunkygoo/Algorithms
/Graphs/rectangleMania.py
2,685
3.765625
4
UP = "up" RIGHT = "right" DOWN = "down" LEFT = "left" # O(N^2) T O(N^2) S def rectangleMania(coords): coordsTable = getCoordsTable(coords, {}) return countRectangles(coordsTable, coords) # O(N^2) T O(N^2) S def getCoordsTable(coords, coordsTable): for coord1 in coords: coord1Table = {UP: [], RIGHT: [], DOWN:...
8a2d38c3f0ca1c4c875f7a52f13b721d1b96cf25
zzz136454872/leetcode
/wiggleSort.py
982
3.640625
4
from typing import List class Solution: def wiggleSort(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ nums.sort() base = len(nums) // 2 if len(nums) % 2 != 0: base += 1 res1 = [] res2 = [] ...
318443155950bd94e6aad6e7494b186852778456
kn2322/topdown-funk
/utilfuncs.py
1,661
3.671875
4
from kivy.vector import Vector from math import hypot """Module used to contain utility functions used for processing in the game. """ # deltay/deltax distance calculations def difference(pos1, pos2): return (pos2[0] - pos1[0], pos2[1] - pos1[1]) # For graphics components, returns the sprite facing direction. de...
9615fa6392605acf304e001cdd24e662f5171173
willcodefortea/dailyprogrammer
/193.py
1,096
4.03125
4
""" (Easy): Acronym Expander http://www.reddit.com/r/dailyprogrammer/comments/2ptrmp/20141219_challenge_193_easy_acronym_expander/ """ import re ACRONYMS = ( ("lol", "laugh out loud"), ("dw", "don't worry"), ("hf", "have fun"), ("gg", "good game"), ("brb", "be right back"), ("g2g", "got to go"...
815115dfd814453d05c5af91a516f8eca5629a93
APARNAS1998/luminardjango1
/python test/calculator.py
1,437
4.1875
4
def addition(): num1=float(input('enter the first number')) num2=float(input('enter the second number')) res=num1+num2 print('result=',res) def substraction(): num1 = float(input('enter the first number')) num2 = float(input('enter the second number')) res = num1 - num2 print('result=',r...
b772bcbf87b00426a98c4f6578d34fe952d4c94f
MrHamdulay/csc3-capstone
/examples/data/Assignment_7/olgmof001/util.py
1,814
3.515625
4
"""Tofunmi Olagoke 29 April 2014 2048 game functions(1)""" def create_grid(grid): for i in range (4): grid.append ([0,0,0,0]) return grid def print_grid (grid): print("+--------------------+") #putting the grid into columns for i in grid: print("|", end="") ...
17b6e252f98a3c628a9254f087712f1b497b8afd
vanyaio/learning_python
/mut_immut.py
1,051
3.796875
4
def underline(): print('_________') #id - identificator for object x = [1, 2, 3] print(id(x)) print(id([1,2,3])) underline() #is - does two vars refer to the same obj? x = [1, 2, 3] y = x print(y is x) #true print(y is [1, 2, 3]) #false underline() x = [1, 2, 3] y = x x.append(4) print(x) print(y) underline() #...
7ca456a91a833b0db662d027abee9991d1ce9417
ReemAlattas/LeetCode-Solutions
/Merge_Two_Lists.py
1,395
4.125
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode "...
0c2f3e6d0ae8ece5066a38c5ad9b96155f6ad000
rjackowens/Code-Snippets
/Testing Dictionary Item Method.py
298
4.03125
4
d = {'H': 1.008, 'He': 4.003, 'Li': 6.94} for elements, weights in d.items(): print(elements, weights) listOfElements = list(elements for elements, weight in d.items()) listOfWeights = list(weight for elements, weight in d.items()) print(listOfElements, listOfWeights) #print(listOfWeights)