blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
4746f743c4e0919f3a088284abcd9453c2ef3bd8
Py-Contributors/AlgorithmsAndDataStructure
/Python/Algorithms/Maths/MarathiToEnglish_number.py
934
4.21875
4
''' English_digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] Below is marathi numbers list This program will convert the input number into english number ''' marathi_digits = ['०', '१', '२', '१', '४', '५', '६', '७', '८', '९'] a = input("Enter marathi digit: ") if a in marathi_digits: print("English Digi...
23a893a893954dc4fea0aaaea5e0f927635b193e
Py-Contributors/AlgorithmsAndDataStructure
/Python/Algorithms/DivideAndConquer/MergeSort.py
1,462
4.46875
4
from typing import List def merge(left: List[int], right: List[int]) -> List[int]: """Merges two sorted lists into a single sorted list. Args: left (list): The left half of the list to be merged. right (list): The right half of the list to be merged. Returns: list: The sorted lis...
df80dd70cdd6836886ac2dc8f5c57f932577f154
Py-Contributors/AlgorithmsAndDataStructure
/Python/Algorithms/SortingAlgorithms/CocktailSort.py
1,384
3.96875
4
""" Title - Cocktail Shaker Sort Algorithm Pupose - Sorts a given array in ascending order. Time Complexity - O(n^2) """ import random class CocktailSort: """ CocktailSort Algorithm Implementation arr: an unordered list output: return list in ascending order Example: >>> sort = C...
4474320e21e8a83c02466c2fe66e28a62988babe
fffeiip/Algoritimos-em-Python
/Sorting/Sorting.py
1,154
3.921875
4
def insertion_sort(lista): for i in range(1, len(lista)): chave = lista[i] k = i while k > 0 and chave < lista[k-1]: lista[k] = lista[k-1] k -= 1 lista[k] = chave return lista def quick_sort(lista): if len(lista) == 0: return lista ...
f0cb5544c0c36a4e8c0f25750f68e4728d8ee8d2
wanjapm/AbruptlyPlanner
/abruptly.py
3,450
3.59375
4
def add_gamer(gamer,gamers_list): if gamer.get("name") and gamer.get("availability"): gamers_list.append(gamer) def build_daily_frequency_table(): return {"Monday":0, "Tuesday":0 ,"Wednesday":0, "Thursday":0, "Friday":0,"Saturday":0,"Sunday":0} def calculate_availability(gamers_list,available_fre...
1be239ea81488d063113d858ea50bee5559e21f8
alitadodo/BTVN2
/exercises1.py
329
4.21875
4
height = float(input("Enter meters: ")) weight = float(input("Input kilogram: ")) BMI = (weight / ((height * height)/10000)) print (BMI) if BMI < 16: print ("Severely underweight") elif BMI < 18.5: print ("Underweight") elif BMI < 25: print ("Normal") elif BMI < 30 : print ("Overweight") else: print...
226c26db6663d6d5573c7af6cd0cd95cec9449da
seyfullah/stockprediction
/experiments/times_passed.py
323
3.65625
4
import time import datetime start = time.time() print("start:" + str(datetime.datetime.now())) end = time.time() hours, rem = divmod(end - start, 3600) minutes, seconds = divmod(rem, 60) print("end: " + str(datetime.datetime.now())) print("Elapsed time: {:0>2}:{:0>2}:{:05.2f}".format(int(hours), int(minutes), seconds...
2185d883e7209cd249717e152153d6dfbed0cfbc
jmsrch8/codeDump
/HumphriesCHW10.py
1,266
4.125
4
#! /bin/python3 #name: HumphriesCHW10 #programmer: Cullen Humphries #date: friday, august 5, 2016 #abstract This program will add records to a file and display records using a module #===========================================================# import time from assign10_module import * # define main def main(): #pri...
8391bc3b513f1384513287a5a96820770f5e1088
Pereirics/Exercicios_Curso_Python
/ex007.py
166
3.640625
4
n1 = float(input('Qual foi a nota do primeiro teste? ')) n2 = float(input('Qual foi a nota do segundo teste?')) print(f'A média dos testes é: {(n1 + n2) / 2 :.2f}')
0db667e718419c8beaf9327421ec68c012ee5711
Pereirics/Exercicios_Curso_Python
/ex011.py
281
3.921875
4
print('Vamos calcular a quantidade necessária de tinta para pintar uma parede!\n') lar = float(input('Insira a largura em metros da parede: ')) com = float(input('Insira o comprimento em metros da parede: ')) print(f'A parede necessita de {(lar * com) / 2 :.2f} litros de tinta!')
812e48810a78c300bf504734b4bf381fbb70ef66
Pereirics/Exercicios_Curso_Python
/ex064.py
297
3.796875
4
cont = soma = 0 n1 = int(input('Escreva um número (999 para parar): ')) while n1 != 999: cont += 1 soma += n1 n1 = int(input('Escreva um número (999 para parar) : ')) print(f'No total foram escritos {cont} números e a soma entre eles dá {soma}!')
97976ba329ab42dfb866897a409713f62c2fa03a
Pereirics/Exercicios_Curso_Python
/ex051.py
174
3.859375
4
termo = int(input('Qual é o primeiro termo da PA? ')) razao = int(input('Qual é a razão da PA? ')) print(termo) for c in range(1,10): termo += razao print(termo)
3b4bd9ad7125520ca1f80dd33e654e2745e53bac
Pereirics/Exercicios_Curso_Python
/ex057.py
300
4.09375
4
sexo = str(input('Qual é o seu sexo? [M/F] ')).strip().upper()[0] if sexo == 'M' or sexo == 'F': print('---FIM---') else: while sexo not in 'MFmf': print('Resposta inválida, por favor tente novamente.') sexo = str(input('Qual é o seu sexo? [M/F] ')) print('---FIM---')
7f8f0e073c79d9b624566ba48f3d1e15139a1db5
Pereirics/Exercicios_Curso_Python
/ex038.py
266
3.9375
4
n1 = float(input('Escreva um número: ')) n2 = float(input('Escreva outro número: ')) if n1 > n2: print('O primeiro valor é o maior!') elif n2 > n1: print('O segundo valor é o maior!') else: print('Nenhum dos valores é o maior! Eles são iguais ;)')
6ad4dcbbc54350b53f555a6ca5246f5a40089957
Pereirics/Exercicios_Curso_Python
/ex037.py
351
4.21875
4
n1 = int(input('Escreva um número: ')) m = int(input("""Escolha um método de conversão: 1 para binário 2 para octal 3 para hexadecimal Insira o valor: """)) if m == 1: n1 = bin(n1) elif m == 2: n1 = oct(n1) elif m == 3: n1 = hex(n1) else: print('Valor inválido!') print(f'O valor convertido para a opçã...
3f5a715dd02640bc20b79de8d9caf679e91a89a5
Pereirics/Exercicios_Curso_Python
/ex061e62.py
337
4.09375
4
termo = int(input('Qual é o primeiro termo da PA? ')) razao = int(input('Qual é a sua razão? ')) n = -1 n1 = 1 while n1 != 0: n1 = int(input('Quantos termos quer adicionar? ')) if n1 == 0: print('---FIM---') else: while n != n1: print(f'{termo}') termo += razao ...
371515037950c318f1f34f4cc8d8564f535c8a0c
Pereirics/Exercicios_Curso_Python
/ex005.py
113
3.640625
4
n1 = int(input('Escreva um número: ')) print(f'O sucessor de {n1} é {n1 + 1} e o seu antecessor é {n1 - 1}!')
2570eb971ff0340aec0c95d7ed8e1144a9b0689a
GinnyGaga/HM-cope_03_OOP
/hm_12_摆放家具_02_房子类.py
1,029
3.765625
4
class HouseItem: def __init__(self,name,area): self.name = name self.area = area def __str__(self): return "家具名字是 [%s],其占地面积是 %.2f平米。" % (self.name,self.area) class House: def __init__(self,house_type,area): self.house_type = house_type self.area = area self....
ba1531a50d1d986f28aa3d3ff86585cfbae711e2
peterhsprenger/vurpy
/training samples/Assignment_3-1.py
139
3.796875
4
hrs = raw_input("Enter Hours:") h = float(hrs) if h <= 40: salary = h*10.5 else: salary = 40*10.5 + (h-40)*(10.5*1.5) print(salary)
408192181f07281e220e2a9b9380617a30b5f594
hujieying/python-learning
/LPTHW/ex33-1.py
615
4.1875
4
# coding:utf-8 # 将这个while循环写成一个函数,将测试条件(i < 6)中的6换成一个变量。 # 使用这个函数重写脚本,并用不同的数进行测试。 # 添加另一个参数,定义第八行的+1,这样可以让它任意递增。 i = 0 numbers = [] maxium = int(raw_input("please input a number!\n")) step = int(raw_input("please input a step!\n")) while i < maxium: print ("At the top i is %d" % i) numbers.append(i) i +...
80dd71a1d3601c72a15e45e8f66f699f3f5bda34
hujieying/python-learning
/LPTHW/ex14-2.py
580
3.609375
4
# _*_ coding:utf-8 _*_ from sys import argv script, user_name = argv prompt = "你的回答是:" prompt2 = ">" print "Hi %s, I'm the %s script." % (user_name, script) print "I'd like to ask you a few questions." print "你喜欢我吗, %s?" % user_name likes = raw_input(prompt) print "你住在哪里呢, %s?" % user_name lives = raw_input(prompt2)...
e76c56aa622d0ab9be9ea3c141a3e3fa3cddc76e
meganle414/Linear-Regression
/regression.py
7,543
3.8125
4
import csv import math import random import numpy as np from matplotlib import pyplot as plt # Feel free to import other packages, if needed. # As long as they are supported by CSL machines. def get_dataset(filename): """ INPUT: filename - a string representing the path to the csv file. RETURN...
67c4ab9c5cd6e1d6d162141bfc80f1a819f51823
jgguida/pythonbirds
/oo/pessoa.py
595
3.703125
4
class Pesoa: olhos = 2 def __init__(self, *filhos, nome=None, idade=None): self.nome = nome self.idade = idade self.filhos = list(filhos) def cumprimentar(self): return 'Olá' @staticmethod def estatico(): return 42 @classmethod def nomes_e_atibutos...
6c9d052903309456a8b5bbd3e5e500b0c22410fa
RakshanaGovindarajan/Graph-Traversal
/Graph.py
12,749
3.640625
4
# File: Graph.py # Description: Implementing various functions for graph # Student Name: Rakshana Govindarajan # Student UT EID: rg38236 # Course Name: CS 313E # Unique Number: 50945 # Date Created: 7 May 2016 # Date Last Modified: 9 May 2016 class Stack (object): def __init__ (self): self.stack =...
74c7800227b1affa1f2d4c015540d03223d7162b
gitPty/hello-world
/scripts01/scripts01/decrypt_encrypt.py
546
3.5625
4
d1='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890' d2='BCDEFGHIJKLMNOPQRSTUVWXYZAbcdefghijklmnopqrstuvwxyza2345678901' def encrypt(string1): ls1=[] for i in string1: if i in d1: ls1.append(d2[d1.index(i)]) print(ls1) return ls1 def decrypt(string2): ls2=[] ...
fd3623435813192c5022a49724421b65958b5311
Nanosplitter/Codingame-Puzzles
/Mime Type/mime.py
378
3.578125
4
table = dict() n = int(input()) q = int(input()) for i in range(n): e, t = input().split() table[(e).lower()] = t for i in range(q): fname = input().lower() fnameArr = list(fname) fnameArr[fname.rfind(".")] = "---" ext = "".join(fnameArr).replace(".", "").replace("---", ".").split('.')[-1] i...
3510d762f697f8f051ce25914eb5453ad94d09d2
HighSaltLevels/Minesweeper
/lib/game_board.py
5,212
3.609375
4
import random import sys from spaces import SpaceValue class GameBoard(object): def __init__(self, rows, cols, mines): if mines >= (rows*cols): raise RuntimeError('Too many mines. You must have 1 or less mines than the total number of spaces') self._rows = int(rows) self._cols...
db0baecd39968cd5646a543009286f56e44b865e
anguszxd/leetcode2
/DivideTwoIntegers.py
1,814
3.671875
4
#coding:utf-8 #Divide two integers without using multiplication, division and mod operator. #If it is overflow, return MAX_INT. #题目要求不能用乘除取余等,所以只能用加减法和位运算完成除法操作 #先想到用加减法做,但这样速度比较慢,在leetcode中超时 def divideTwoInts(dividend, divisor): intMax, intMin = 2147483647, -2147483648 sign = 1 if 0 in [dividend, divisor]: ret...
61674cd42f21f2984c298267331f4ff44e33e0e5
anguszxd/leetcode2
/SwapNodesInPairs.py
656
3.890625
4
#coding:utf-8 #Given a linked list, swap every two adjacent nodes and return its head. #For example, #Given 1->2->3->4, you should return the list as 2->1->4->3. #Your algorithm should use only constant space. #You may not modify the values in the list, only nodes itself can be changed. import LinkList as LL def ...
eed51f978b5435095b8a8447d6a59a2fbc3c15b5
anguszxd/leetcode2
/PowXN.py
241
4
4
#coding:utf-8 #Implement pow(x, n). def myPow(x, n): if n < 0: x = 1/x n = -n cur = x ans = 1 while n > 0: if n & 0x1: ans *= cur cur = cur*cur n = n >> 1 return ans x = 34.00515 n = -3 print myPow(x, n) print pow(x, n)
65b54b92b728e9641e659be060e30ec6741da972
anguszxd/leetcode2
/addTwoNumbers.py
901
3.734375
4
#coding:utf-8 #You are given two linked lists representing two non-negative numbers. #The digits are stored in reverse order and each of their nodes contain a single digit. #Add the two numbers and return it as a linked list. #Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) #Output: 7 -> 0 -> 8 class ListNode: def __init__(...
9c10af82a82570c919d83811dff2802a6f708e03
anguszxd/leetcode2
/PermutationsII.py
738
3.859375
4
#coding:utf-8 #Given a collection of numbers that might contain duplicates, return all possible unique permutations. #For example, #[1,1,2] have the following unique permutations: #[1,1,2], [1,2,1], and [2,1,1]. #Solution:跟前面的全排列类似,改进的地方在于先判断放在第一位的元素有没有出现过, #如果已经使用过了,就跳过该循环 def permute(nums,ans,path): if len(nums)...
1e0a454b1ec5c026abb3c0561317981bb329140d
Nemisis7/Lists
/lists4.py
311
3.890625
4
import random myList = ['anna','ben','charlie','dennis','edward','francis'] for i in range(len(myList)): name = myList[i] #print(name[len(name) - 1]) #print(name[0]) #print(len(name)) print(name[random.randint(0,len(name)-1)]) https://docs.python.org/2/tutorial/datastructures.html
251bfd3225531b67568ecb419113ccd5a99cf6b2
jonnytaddesky/taskPython
/ugol.py
654
4.21875
4
# Напишите программу , в которой по извесной начальной скорости # V и времени полета тела T определяется угол aльфа под которым # тело брошено по отношению к горизонту (воспользуйтесь соотношением a = arcsin(gT/2V) ). # Ниже показан вывод программы, которая у вас должна получиться: import math g = 9.8 v = float(in...
f582b5973f493e2b4adf1b9d2e3c4203f455ad07
jonnytaddesky/taskPython
/func.py
422
3.71875
4
import numpy as np def calc(x, m): result = 1 for j in np.arange(m): result *= x return result def power(): z = 0 for x in np.arange(-1.1, 0.3, 0.2): for m in np.arange(1, 5, 1): z = calc(x, m)*calc(np.sin(x*m),m) print('Значение функции = {} При m = {}'...
621ab604f55b1efa819b2ef09176389adb082a90
mikaelshall/python-challenge2
/PyBank/PyBank.py
1,862
3.5625
4
# Import Modules/Dependencies import os import csv #Files to load infile = os.path.join('/Users/mikaelshall/Desktop/unc-peace-data-pt-08-2020-u-c/02-Homework/02-Python/Instructions/PyBank/Resources/budget_data.csv') outfile = os.path.join("analysis", "pybank.txt") monthsTotal = 0 netTotal = 0 previousBudget = 0...
c24a9fec24669e3258d9a75bba3c96c9736edefc
r3sult/My-AI-Experiment
/clustering/kmeans/kmeaners.py
5,824
3.515625
4
""" created by : ridwanbejo deskripsi : contoh implementasi algoritma K-Means untuk clustering data """ # library yang dibutuhkan untuk clustering k-means import math import matplotlib.pyplot as plt import numpy as np # fungsi - fungsi yang terlibat dalam perhitungan clustering k-means def get_euclidean_distance(p...
dbdd36983477cda4f79005891bc432a7ddc542fa
UnderGrounder96/mastering-python
/03. Implemented Data Structures/1.Stack.py
316
4.1875
4
##### 13. STACKS # Last In First OUT stack = [] stack.append(1) stack.append(2) stack.append(3) print(stack) last = stack.pop() print(last) print(stack) print(stack[-1]) # getting the item on top of the stack # checking if the stack is empty if not stack: # that means we have an empty stack # do something
6c931d306147d284fb67fbb1ed411944244d179c
UnderGrounder96/mastering-python
/06. Looping/1.for.py
3,547
4.5625
5
string = "Sammy" # EXAMPLE 1 for letter in string: print(letter) # EXAMPLE 2 # FOR loop + break, continue, pass - add additional functionality for various cases. # a) BREAK: breaks out the current closest enclosing loop. for letter in string: if letter == 'a': break print(letter) # b) PASS - does nothing at al...
823f785ada0a4688d09c16e06e7eed11c3c5b8ac
UnderGrounder96/mastering-python
/10. OOP/05.ClassVsInstanceMethods.py
539
4.1875
4
# 5. CLASS VS INSTANCE METHODS class Point: def __init__(self, x, y): # this is an instance method self.x = x self.y = y # 1. defining a Class Method @classmethod # this is called a decorator and it's a way to extend the behavior of a method def zero(cls): return cls(0, 0) def draw(se...
30882ebeb9098c8a1dfd0e587dbc8b23d3c4b00b
UnderGrounder96/mastering-python
/07. Functions/2.args.py
513
4.5
4
# *args (arguments) # *args behaves like a tuple of parameters that are coming in. # *args allows us to take random numbers of arguments. # * means a collection of arguments # EXAMPLE 1 def myfunc(*args): return sum(args) myfunc(40,60,100) # EXAMPLE 2 def myfunc(*args): for item in args: print(item) myfu...
e62df20fb6734344ac7020c131975c31d9910677
UnderGrounder96/mastering-python
/10. OOP/16.MultipleInheritance.py
495
3.765625
4
# 16. MULTIPLE INHERITANCE - which should be avoided!! class Employee: def greet(self): print("Employee greet") class Person: def greet(self): print("Person greet") class Manager(Person, Employee): # this is a multiple inheritance pass manager = Manager() manager.greet() ## A good example of Multi...
eb3fb66e3983c8ea0d131c308cd32b0ed8c30b0c
UnderGrounder96/mastering-python
/02. Built-in Data Structures/4.sets.py
963
4.625
5
# EXAMPLE 1 myset = set(); myset.add(1) myset.add(2) myset.add(3) mylist = [1,2,3,4,5] myset2 = set(mylist) # EXAMPLE 2 numbers = [1, 1, 2, 2, 4, 3] print(numbers) # converting the list into a set set_uniques = set(numbers) print(set_uniques) # defining a new set set_new = { 1, 4} set_new.add(5) set_new.remove(5) l...
e083ac37956b22d92143b8cd5a89a807a5c15a01
asazonov28/andrei
/Student/Lesson2.py
2,463
4.1875
4
# string_sample = 'Hello World' # number = '12345678' # number2 = '-8-7-6-5-4-3-2-1' # print(len(string_sample)) # print(len(number)) # # # print(string_sample[6:11]) # # print(string_sample[-7:]) # # print(string_sample[0:11:2]) #индексация строки с шагом 2 # # print(string_sample[::-1]) #индексация с обратным ша...
1e47c5232df87b9f3747b753eab5e49403a0dfe3
bhaktij24/gitupload
/UserFunction.py
9,498
3.703125
4
## import statements import sqlite3 import Review import string ## Class for user functionalities class UserFunction: global conn #connect sqlite3 conn = sqlite3.connect('movie.db') global getRating #init function of user module def __init__(self,idRole): #fetch useri...
58827d7ec2c68316ea7ac763f92646c49012776f
ZeweiChu/julyedu-python-datascience
/Syntax/loops/fibonacci.py
219
3.78125
4
print("while loop:") fibs = [] i = 0 j = 1 while i < 500: fibs.append(i) tmp = j j = i + j i = tmp print(fibs) print("for loop:") fibs = [0, 1] for i in range(2, 15): fibs.append(fibs[-1] + fibs[-2]) print(fibs)
5fa1c2c25658327ae7fb3e65d3054c7b4cd13b09
ZeweiChu/julyedu-python-datascience
/Syntax/function-module/fib.py
343
3.640625
4
import code def fib(n): a, b = 0, 1 for i in range(n): print(a, end=" ") a, b = b, a+b print() # fib(5) # fib(10) # fib(30) # fib(100) def print_all(*args): print(type(args)) print(args) # print_all("hello", "world", "julyter", "notebook") def unpack_args(a, b): print(a, b) r = [2,5] r = 2,5 # unpack_ar...
942962012f2cdc47d6426fe2029599f715f9d112
Cynthyah/Exercises
/BinaryGap.py
696
3.96875
4
# Find longest sequence of zeros in binary representation of an integer. # Write a function that return the length of the longest binary gap # N = 529 the binary is 1000010001 -> the longest binary gap is 4 # N = 20 the binary is 10100 -> the longest binary gap is 1 # N = 9 the binary is 1001 -> the longest binary ...
72e18d8d790ba5b03da904cf71f6b113fb9227fa
Cynthyah/Exercises
/MaxProductOfThree.py
705
3.609375
4
# MaxProductOfThree - Maximize A[P] * A[Q] * A[R] for any triplet (P, Q, R). # A = [-3,1,2,-2,5,6] # (0, 1, 2), product is −3 * 1 * 2 = −6 # (1, 2, 4), product is 1 * 2 * 5 = 10 # (2, 4, 5), product is 2 * 5 * 6 = 60 # the function should return 60, as the product of triplet (2, 4, 5) is maximal. # Important # N is...
f07cea8a3d062fbfe23802f24342f9f81ef9a12a
Cynthyah/Exercises
/LongestCommonSubsequence.py
670
3.765625
4
# LongestCommonSubsequence.py # The longest common subsequence (LCS) problem is the problem of finding the # longest subsequence common to all sequences in a set of sequences # (often just two sequences). def lcs(s1,s2): long = 0 comon = [] for c1 in s1: if c1 in comon: next fo...
6c8c0c4190026a98a4e4c7e240208e06dea5c4f7
mludvig/guess-number-gym
/gym_guess_number/envs/guess_number_env.py
4,834
3.734375
4
#!/usr/bin/env python3 """ Simple Guess a Number game Observation is [NONE, LOWER, HIGHER, CORRECT] Action space is [0 .. MAX_NUMBER] The reward 0 until the last episode, then Action distance from Target number. The distance is absolute and negative, ie the closer the last action to target the higher reward. """ i...
b300ff977d451273860542eae6dc12c872c0b825
albertwir360/Atomic_Scale_Simulation
/[4]- Random Number Generators/Code_Data/test_chisquare.py
2,339
4.03125
4
import numpy as np def my_CheckRandomNumbers1D(rand_array,NB): """ This function can be reused later for larger data set Input: rand_array: array of length N NB: number of bins per dimension (for 1D we need NB bins in total) Output: the chi-squared value of the rand_array, with NB evenly ...
e498f03434f5d57c2666941f548cfd09d9633eb3
Efun/CyberPatriotTutoring
/practice/archive_10/practice_10_7_2020.py
952
4
4
#Linear Search Practice def fruitSearch(): fruitsList = ["apple", "banana", "orange", "kiwi", "watermelon", "pineapple"] userInput = input("Which fruit do you want to find?") notFound = True #how do we know if something is not found? for x in fruitsList: if userInput == x: pr...
c30c0b73aa515d1541962322d6b33079008d2a66
Efun/CyberPatriotTutoring
/practice/Archive_8-9_2020/practice_9_27_2020.py
1,624
4.1875
4
from classes.BankAccount import BankAccount # test = BankAccount('a', 'a', 100) # print(test.balance) # write a list of 5 elements containing tennis player names tennisPlayers = ["serena williams", "roger federer", "rafael nadal", "novak djokovic", "rod laver"] #print the second element of this list #print (tennisP...
155359354b2395e4c1b887ad8cb8c9312cb3f0fc
FisicaComputacionalPrimavera2018/ArraysAndVectorOperations
/vectoroperationsUpdated.py
1,620
4.28125
4
import math #### FUNCTIONS # The name of the function is "norm" # Input: array x # Output: the norm of x def norm(x): tmp = 0 for v in x: tmp += v*v norm_x = math.sqrt(tmp) return norm_x def vectorSum(x, y): #z = x + y This doesn't work for arrays! # First we check if the dimensions of x and y # ...
c87eff9c60287f0f00de399ede287ad1c24adb35
Ecohnoch/Compilers-homework
/lispy/parse.py
2,380
3.6875
4
# Parsing Module # A Scheme List is implemented as a Python list # A Scheme Number is implemented as a Python int or float Symbol = str # List = list # Number = (int float) # Class for Lisp common symbols # class Symbol(str): pass # Symbol = str # List = list # Number = (int, float) # Class for Lisp common symbols #...
2ebe4673640d35ddb7bc0a181247888c17bd126f
dpslwk/tech-blog-roll-the-dice
/roll_the_dice/cli.py
1,767
3.578125
4
import typer from .dice import roll, roll_from_string app = typer.Typer() @app.command("hello") def hello_world(): """our first CLI with typer! """ typer.echo("Opening blog post...") typer.launch( "https://pluralsight.com/tech-blog/python-cli-utilities-with-poetry-and-typer" ) @app.com...
dc03bce119c16d0d47c7d2caec844b47d50d2ae6
redpoint13/ProgrammingFoundations
/myshapes.py
304
3.765625
4
import turtle def draw_frac(): circle = turtle.Turtle() circle.shape("classic") circle.color("orange") circle.speed(100) for i in range(0,36): circle.circle(100) circle.right(10) carpet = turtle.Screen() carpet.bgcolor("green") draw_frac() carpet.exitonclick()
b1fe4ed0a110d5969e2d6d184a4c5e083ffdee18
abelloma/python-challenges
/PyPoll/main.py
2,134
3.6875
4
import os import csv candidate = [] unique_candidate = [] csvpath = os.path.join('Resources','election_data.csv') text_file = open("Output.txt", "w+") with open(csvpath, newline='') as csvfile: # CSV reader specifies delimiter and variable that holds contents csvreader = csv.reader(csvfile, delimiter=',')...
256adde8cca2a19127259c91d2c3756f750bbcb5
isaac-davis-15/APCSP
/network.py
2,693
3.5625
4
#======================================================================================================= #Isaac Davis 4/10/18 # #This script contains functions that can be used by other Python scripts. #The functions calculate all of the math and algorithms for the neural network to function. #This script is specific...
60ce27f843b92a8a684838f0b1db2a9ff785d2d2
courtney-mcquade/CMPT-120L-902-21S
/Assignments/Assignment 6/leap_year.py
333
4.03125
4
def leap_year(year): if (year % 4 == 0) and not (year % 100== 0): return("Is a leap year") else: return("Is not a leap year") if __name__ == "__main__": years = [2000, 1994, 1912, 3002, 1700, 1400] answers = [] for year in years: answers.append(leap_year(year)) p...
a7ab6003f079582b533334ff53af75b524bd63e1
courtney-mcquade/CMPT-120L-902-21S
/JupyterNotebooks/Lessons/testing.py
490
3.890625
4
rainbow = ["red", "orange", "yellow"] for color in rainbow: print(color.title()) for number in range(0,12,3): print(number) a = True b = False if a and b: print("this") elif b and False: print("b") elif b or False: print("c") elif a and True: print("finally this") arr = [2,5,6,1,4,3] ...
92fbd265c509e98191bfb4acc095b6f0995dc6d5
bitPanG98/Ejercicios
/Python/Algoritmo-FCFS/metodo2_fcfs/modulos/util_graficas.py
2,017
3.546875
4
#!usr/bin/env python3 # -*- coding: utf-8 -*- #------------------------------------------------------------------------------------------------- # author: SoftPanG # correo: bitpang98@gmail.com #----------------------------------------------------------------------------------------------- #---------------------- fu...
4718dcdb6553af3f45972667ea3155d20eb73402
elijahanderson/ascii-converter
/converter.py
1,927
3.890625
4
""" Python program using OpenCV to convert a pixel image to an ASCII image. ~~ by Eli Anderson ~~ """ import cv2 as cv import numpy as np import time # setup np.set_printoptions(threshold=np.inf) ascii_vals = [' ', '.', "'", '^', ',', ':', ';', '!', 'i', 'l', '<', '>', 'u', 'o', 'x', '+', 'z', 'k', 'U', 'O', ...
ef94f72a932dbf7723422f353c5bb3d5481e06a6
peshin-ai/prac9
/sort_files_2.py
1,151
3.65625
4
""" CP1404/CP5632 Practical Demos of various os module examples """ import shutil import os # Sorting into folder that are generally named def version_2(): """Demo os module functions.""" print("Starting directory is: {}".format(os.getcwd())) # Change to desired directory os.chdir('FilesToSort') ...
5249f6c1d2650dd6bb311112c8fe29c7382ab5bd
garydoranjr/pyddl
/missionaries_cannibals_example.py
4,157
3.515625
4
#!/usr/bin/env python """ Example of using PyDDL to solve the "Missionaries and Cannibals" Problem. A boat must transport a group of 3 missionaries and 3 cannibals across a river, but at no time can the cannibals outnumber the missionaries at either side of the river. """ from __future__ import print_function from pydd...
8c0e6b63e677f2fa5ed5af7504b6fcae65c134ba
GabrielMarquesss/Exercicios-Python
/ex029.py
414
3.71875
4
#Programa que leia velocidade de um carro #Se ele ultrapassar 80km/h mostre uma mensagem dizendo que foi multado #A multa vai custar 7,00 por km acima do limite vel = int(input('Digite qual a velocidade capturada pelo radar móvel: ')) multa = (vel - 80) * 7.00 if vel > 80: print('Acima do limite de velocidade ({}...
9c75ac81f50789738e4f938004a72317139861ed
GabrielMarquesss/Exercicios-Python
/ex043.py
759
3.859375
4
#Programa que calcula IMC e mostre status #Abaixo de 18.5 abaixo do peso #entre 18.5 e 25 peso ideal #entre 25 e 30 sobrepeso #entre 30 ate 40 obesidade #acima de 40 obesidade morbida peso = float(input('Digite o seu peso em Kg: ')) altura = float(input('Digite sua altura em M: ')) imc = peso/(altura**2) if imc < 18....
6d1e5e803b5259304a3e170857873a97dee8fabf
GabrielMarquesss/Exercicios-Python
/ex015.py
408
3.703125
4
#Programa que calcula a quantidade de KM percorrico, # a quantidade de dias alugado. Preço a pagar: carro = 60/dia + 0,15 por km dias = int(input('Por quantos dias o carro foi alugado? ')) km = float(input('Quantos Km foram rodados com o carro? ')) pay = (dias * 60) + (km * 0.15) print('O carro foi alugado por {} dia...
6e5e27e677b1b06554c74769c8f83aa9d4711491
GabrielMarquesss/Exercicios-Python
/ex005.py
178
3.96875
4
#Programa que leia um npumero e mostre seu sucessor e antecessor n = int(input('Digite um número: ')) print('{} é o antecessor de {}, e seu sucessor é {}'.format(n-1,n,n+1))
3b5fa35779f64ed48e9e602a290c35374e2ab2ba
bhasin85/Teachable
/1.Fundamentals/EvaluateReversePolishNotation.py
1,000
3.59375
4
class Solution: def evalRPN(self, tokens: List[str]) -> int: i = 0 while i < len(tokens): print("i:"+str(i)+ " tokens:"+str(tokens)) if not tokens[i].isnumeric() and tokens[i] != "(" and tokens[i] != ")": # Swap digit with operator tem...
77d3c7c625dc887ddc8aaa848f0d199fbfa1a06b
JinalShah2002/MLAlgorithms
/LinearRegression/Prof.py
2,211
4.34375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author Jinal Shah Suppose you are the CEO of a restaurant franchise and are considering different cities for opening a new outlet. The chain already has trucks in various cities and you have data for profits and populations from the cities.You would like to use ...
751f1777faad91870b7079238aa8d840848021b7
prabhatpal77/Complete-core-python-
/typeconversion.py
390
4.125
4
#Type conversion function converse the data in the form of required format in the data is possible to convert.. a=input("enter int value") print(type(a)) b=int(a) print(type(b)) c=input("enter float value") print(type(c)) d=float(c) print(type(d)) i=input("enter complex value") print(type(i)) j=complex(i) print(type(j)...
0d63f4ba68bd568c1d41c54896ab6b58fd376900
prabhatpal77/Complete-core-python-
/tupletype3.py
351
3.921875
4
# nested tuple with for loop.. x=(10, 20, 30, 40, 50, 60) print(x) print(x.count(20)) print(x.count(75)) print(x.index(40)) y=((10, 20, 30),(40, 50, 60),(70, 80, 90)) print(y) for p in y: for q in p: print(q, end=" ") print() for a, b, c in y: print(a, b, c) z=((10, 20, 30),[40, 50, 60],(70, 80, 90)...
5445ed3ec2ed63df36505ecd9b67a2cbca425c50
prabhatpal77/Complete-core-python-
/dictlist.py
239
3.921875
4
# distionary type with list type.. x={"java":["spring","sturts","jsf"], "python":["django","flask","pyramid"], "hadoop":["hive","pig","sqoop"]} print(x) for k,v in x.items(): print(k) print("____") for p in v: print(p)
0f5463149ed49570c867f233e6dbc145da9104d6
prabhatpal77/Complete-core-python-
/identityope.py
470
4.125
4
#Identity operators are used to compare the addresses of the objects which are pointed by the operators .. #there are 2 identity operators. # 1. is 2. is not a=1000 b=2000 c=3000 d=3000 p=[10, 20, 30] q=[40, 50, 60] x=[70, 80, 90] y=[70, 80, 90] print(a==b) print(a!=b) print(a is b) print(a is not b) print(c==d) print(...
5ea07749bc0c7b51114de6f0f2b91852120074cf
prabhatpal77/Complete-core-python-
/func3.py
250
3.6875
4
#if we don't define any return statement sxplicitly with in the function or if user define return statement # is not executed bydefault a function return the default value called none: def add(a, b): c=a+b print(c) p=add(1000, 2000) print(p)
4a2bc016609a7be2403a85798397237a1dfb598c
prabhatpal77/Complete-core-python-
/settype3.py
371
3.53125
4
# other opearations on set.... x={1, 2, 3, 4, 5} print(x) y={4, 5, 6, 7, 8} print(y) print(x.union(y)) print(x|y) print(y.union(x)) print(y|x) print(x.intersection(y)) print(x&y) print(y.intersection(x)) print(y&x) print(x.difference(y)) print(x-y) print(y.difference(x)) print(y-x) print(x.symmetric_difference(y)) prin...
98f9490ecf83371c8e2454136be496bec3a67301
prabhatpal77/Complete-core-python-
/userdefexcep.py
770
3.78125
4
# Defining user defined exception class, rising that exception explicitly and handle that exception is comes # under user defined exception implementation.. # program- Gussing random no. in user definee exception. import random class ValueTooSmallError(Exception): pass class ValueTooLargeError(Exception): pass ...
94492c43f4f858d9e46e6484a4faf4cb1585d487
prabhatpal77/Complete-core-python-
/filehandl.py
323
4.4375
4
# Through the python program we can open the file, perform the operations on the file and we can close the file.. # 'r', 'w', 'a', 't', 'b', '+' for operations on file # Open function opens the given file into the specified mode and crete file object.. # reading from file... x=open("myfile.txt") print(x.read()) x.close...
0c461a6274e3c60b299e190a0d43e96043a9c1ff
nandinikoti/opencv-face-detection
/take_photo.py
1,495
3.71875
4
import numpy as np import cv2 import time """ Take A Photo This script uses OpenCV to take a picture from a webcam or USB camera device. """ def take_photo(camera_port=0): """ Captures an image from a web camera using OpenCV """ camera = cv2.VideoCapture(camera_port) print("Say cheese") time...
c9d840e2970a21f846d0bb2dc3ea2dc8bc1a95f3
roman79/things
/finance/montecarlo/test_bid_ask.py
1,933
3.671875
4
#!/usr/bin/python # -*- coding: utf-8 -*- """test_bid_ask.py: simulation for bid_ask.py""" __author__ = "Niall O'Connor" import unittest import bid_ask class TestBidAsk(unittest.TestCase): """ Test the bid and ask generators. Test order matching. Test spread determination. """ def test_bids(...
d3e7f7fa3294616c4f54deaef178500dea20d363
Silvia-man/test-
/python习题/仅菜鸟上的/9.py
311
3.921875
4
#9.题目:暂停一秒输出。 #程序分析:使用 time 模块的 sleep() 函数 import time l=[1,2,3,4] for i in range(len(l)): print (l[i]) time.sleep(1) # 暂停一秒输出 myD = {1: 'a', 2: 'b'} for key, value in dict.items(myD): print (key, value) time.sleep(1) # 暂停 1 秒
888995f1b1f1805f2c26e889e58e4bb94899bc7d
Silvia-man/test-
/python习题/仅菜鸟上的/56画圆.py
389
3.625
4
# 56.题目:画图,学用circle画圆形。    if __name__ == '__main__': from tkinter import * canvas = Canvas(width=800, height=600, bg='pink') #canvas.pack(expand=YES, fill=BOTH) canvas.pack() k = 1 j = 2 for i in range(26): canvas.create_oval(300 - k,250 - k,300 + k,250 + k, width=2) ...
d76606358969bbb561f71ed6597219769876c74c
Silvia-man/test-
/python习题/仅菜鸟上的/11.兔子问题.py
147
3.65625
4
# 11.兔子问题(斐波那契) f1 = 1 f2 = 1 for i in range(1,22): print ('%12ld \n%12ld' % (f1,f2)) f1 = f1 + f2 f2 = f1 + f2
d8544abebe70a400532f0641202a9f6cd04920e3
Silvia-man/test-
/python习题/其余题/^80数组移零.py
344
3.78125
4
# 80.给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。 nums=[0,3,0,6,7,2,0,11] def yl(nums): arr=[] brr=[] for i in nums: if i==0: brr.append(0) else: arr.append(i) arr.extend(brr) return arr print(yl(nums))
9070daf4b88410b724f3f2bd8b68591b260470f1
Silvia-man/test-
/python习题/仅菜鸟上的/29.py
215
3.796875
4
# 29.题目:给一个不多于5位的正整数,要求:一、求它是几位数,二、逆序打印出各位数字。 s=input("Please input a string:") s=list(s) a=len(s) #s.reverse() print(a,'\n',s[::-1])
780f5a8108c8ca11d8a50d932fe6d250349ccbd7
ixxra/programming-curse-problems-13
/sucesion_y_serie/suma.py
96
3.640625
4
n = input('Valor de N: ') r = input('Valor de r: ') print sum([r**i for i in range(1, n + 1)])
e3df1ec7edc8855de24ee507209d91966650592c
suzibrix/lpthw
/ex16b.py
1,457
4.09375
4
### ex 16 land-- VLL was here # Study Drill #1 complete # Study Drill #2 complete (it is called 16-reader.py # Study Drill #3 -- look out. concatinate read processes! # Open sys and use argv in this program from sys import argv # Use filename attribute to argv script, filename = argv # Reminds user that they are e...
cf89d81fa5fa2fc86a2770f9cf42954ffa049599
suzibrix/lpthw
/ex4.py
1,660
4.21875
4
# This line assigns 100 to the variable "cars" cars = 100 # This statement assigns the number "4.0" to the variable "space_in_car" space_in_a_car = 4.0 # Assigns the number 30 to the variable "drivers" drivers = 30 # Assigns the number 90 to the variable "passengers" passengers = 90 # Assigns the difference of varia...
f41b9a52f3b45cb0b7ce5622378ccd1100b658d9
suzibrix/lpthw
/ex6br.py
2,360
4.09375
4
# exercise 6.br == the second edit by VLL (or VLK, take your pick) ## This file contains errors. For a reason. See if you can find them. ## There are supposed to be three in all. # Here is the first variable {types_of_people}, defined as 10 (the number) types_of_people = 10 # Variable x is defined by an "f- string" wh...
e89db0bd8eab5b9573bfdc6403dfd8ff0d55dea6
younesben/tkinter-tutorial
/tkinter/buttons.py
2,059
3.90625
4
from Tkinter import Tk, RIGHT, BOTH, RAISED from ttk import Frame, Button, Style #################### Buttons class #################### class Buttons(Frame): def __init__(self, parent): # Calling the constructor method of the inherited class. Frame.__init__(self, parent) # In...
8d33594f74c58174b463aba1f3b365e4ef01fd5e
micgainey/Towers-of-Hanoi
/towers_of_hanoi_count.py
1,979
4.15625
4
""" Towers of Hanoi rules 1. You can't place a larger disk onto a smaller disk. 2. Only 1 disk can be moved at a time. Towers of Hanoi moves is: 2^n - 1 OR 2 * previous + 1 example with 3 disks 3 towers: A. B. C. Starting point: 1 2 3 A B C ...
2e3eb4ee195c70ca99dd1237dac1c1ce1859e0a5
Gen1a/CS50X_Problem_Sets
/problem_set7/houses/roster.py
629
3.78125
4
from cs50 import SQL from sys import argv, exit if len(argv) != 2: print("Usage: python roster.py house\nTry again.") exit(1) else: # Open the students.db file to prepare for usage db = SQL("sqlite:///students.db") # Read house from command line argument and covnvert to string house = str(argv[...
a5305f23d0038814f95207a3dba6199913518cbd
thewchan/impractical_python
/ch4/storing_route_cipher_key.py
1,387
4.25
4
""" Pseudo-code: ask for number of length of key initiate defaultdict for count in length of key ask for column number store as temp1 ask for direction store as temp2 defaultdict[temp1] = temp2 """ from collections import defaultdict while True: key_len = input("Enter length of key: ") try: ...
1b5c79c714f71c3da093510f6015ec5107605596
dev92FerFlores/Tic-Tac-Toe
/Tic-Tac-Toe.py
4,478
4.34375
4
#Implementacion de juego Tic-Tac-Toe en Python. '''El tablero se arma usando una matriz, donde las claves serán la ubicación (por ejemplo: arriba a la izquierda, a la mitad a la derecha, etc.) y sus valores iniciales serán espacios vacíos y después de cada movimiento cambiaremos el valor de acuerdo a la elección ...
f7aaeda2943f7d3ca392fbc4bbd993adefabbc95
mohabouje/smartmeet-python
/smartmeet/io/decoder.py
2,114
3.625
4
from soundfile import SoundFile class Decoder: """This class is an interface to read data from an audio file""" def __init__(self, file: str): """Creates an instance of a Decoder source with the given configuration Args: file_name (str): Input file name frames_per_buff...
c72ceeca245c2c3f54de6bf7cd4db80821186888
pardhasaradhim/qr-codes
/notebooks/re_demo_20200520-final.py
389
3.546875
4
# -*- coding: utf-8 -*- """ Created on Wed May 20 09:13:01 2020 @author: sarad """ import re fp = open('emailinventionstory.txt','r') fp.seek(0) text = fp.read() print(text) fp.close() results = re.findall(r'email',text) count = len(results) print('Number of times email appeared: ', count) cit...
7a50289e32b984910776f0179509b9a3a68a1b8f
yash-chandak/high-school-projects
/missing_word_finder.py
524
3.75
4
def missingWords(s, t): arrS = s.split() len_arr = len(arrS) arrT = t.split() arrFinal = [] count = 0 while(count < len_arr): if (len(arrT) == 0): arrFinal.append(arrS[0]) arrS.pop(0) count += 1 elif (arrS[0] == arrT[0]): arrS = arrS[1:] if (len(arrT) != 1): ar...
48f2f1de1801e1b46f0a1e3c7c600573eefcf437
svimal2106/nanodegree
/lesson7/media.py
972
3.59375
4
class Video: """ Base class which denotes a video entity """ def __init__(self, title, duration, storyline, rating=None): self.title = title self.duration = duration self.storyline = storyline self.rating = rating class Movie(Video): """ Movie class which holds ...