blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
bdfb9a6086705fc23c629a16c1b1db7983e7d2a3
CODEvelopPSU/Lesson-2
/DragonAdventure.py
1,498
4.15625
4
import time print("Welcome to the Dragon Cave Adventure!") time.sleep(2) print("You awake inside a cave and see a dragon!") time.sleep(2) print("It looks like it's asleep...") time.sleep(1) print("You look for a way out. Maybe you could climb over the dragon's tail...") choice1 = int(input("1 - Explore the ca...
fbb1e8227bc21a0c21e3ac074f45a52ad030131a
solsword/dunyazad
/prototypes/simplified/verbs.py
2,181
3.984375
4
""" verbs.py Code for handling verbs and conjugation. """ from utils import * from eng_base import * def base(verb): return verb def add_s(verb): if ( any(verb.endswith(e) for e in ["s", "z", "ch", "sh"]) or verb[-2] in consonants and verb[-1] == "o" ): return verb + "es" elif verb[-2] in conso...
f46b1a6b49bcd8bf93b8397531f39e50964dcbf0
augus2349/CYPFranciscoMC
/libro/ejemplo2_4.py
146
3.546875
4
SUE = float(input("ingrese el sueldo ")) if SUE < 1000: NSUE = SUE * 1.15 else: NSUE = SUE * 1.12 print(f"el nuevo sueldo es: { NSUE }")
46f567222aefe95f8dc2d699a94de6ce003823f3
jxie0755/Learning_Python
/ProgrammingCourses/PythonCrashCourse/C6_Dict_set.py
646
3.703125
4
favorite_languages = { "jen": "python", "sarah": "c", "edward": "ruby", "phil": "python", } for name in favorite_languages.keys(): # 可以不写keys,默认也是寻找keys print(name.title()) print() for language in favorite_languages.values(): # value必须要标明 print(language.title()) # 这样会出现重复的language, 可以使用set print() #...
4354bb2ea1c70a67c56590218a5d4e59e51a90bf
productivityboyz/Blackjack
/card.py
2,555
4.375
4
"""This module contains the 'Card' class and related methods. """ import pandas as pd import numpy as np class Card: """ A class defining the properties of a card object. On initialisation, the internal attributes for the suit, rank, value and deck number of the Card are defined based on the input variables. ...
0170145561ba13e15cb46c6cadf22169f1770109
davdevor/AIProject
/src/Oracle/Oracle.py
662
3.734375
4
import json import random def readPoems(): word = input("Enter a topic: ") word = str.lower(word) file = open('poetry.json',encoding = 'UTF-8') data = json.load(file) poems = [] for x in data: if(str.lower(x['classification'])==word): poems.append(x['text']) conti...
04f904df7f6abcaf7eb692fa7f16a2f9ba49f102
professional2684/DK
/BinaryTree.py
1,764
3.875
4
class Custom_Node: def __init__(self, data): self.left = None self.right = None self.data = data def insert_tree(self, data): if self.data == None: self.data = data elif data > self.data: if self.right is No...
798f43b157d8124b1c2788aa552a93c8cc374a69
ilarysz/python_course_projects
/object_oriented_programming/oop/composition.py
358
3.765625
4
class Leg: pass class Back: pass class Chair: def __init__(self, num_legs): self.legs = [Leg() for number in range(num_legs)] self.back = Back() def __repr__(self): return "It's a chair with: \n" \ "{} legs and \n" \ "{} back.".format(len(self.l...
e254264a20f73e2c70ad1a5154770877d31dae16
SoyUnaFuente/c3e2
/main.py
322
4.0625
4
name = str(input("Enter your name: ")) age = int(input("Enter your age: ")) ticket_price = 0 if age <= 4: ticket_price = 0 elif age <= 18: ticket_price = 1.50 elif age >= 60: ticket_price = 1 else: ticket_price = 2 print(f"The Customer: {name} has: {age} years and his ticket cost is: $ {ticket_price}"...
5e1fbbed2f038ea59f7531ca2b8e1511ca39e6d9
YanSongSong/learngit
/Desktop/python-workplace/从1加到100的递归写法.py
176
3.671875
4
#从1加到100的递归写法 def recurrency(x,result): if(x==1): return result+1 else: return recurrency(x-1,result+x) print(recurrency(100,0))
d1eb7447eeb2042c9b1ba57c40e872db884244e6
TanmayNakhate/headFirstPython
/sanfoundry.com/sanFoundryDict.py
1,329
3.859375
4
class dictProg(): def addinfo(self): """Python Program to Add a Key-Value Pair to the Dictionary""" newdict ={1:"aa",2:"bb",3:"cc",4:"dd",5:"ee"} newdict[6]="ff" newdict.update({7:"gg"}) print(newdict) def dict_combo(self): newdict = {1: "aa", 2: "bb", 3: "cc",...
806824333df95a288086699d34e10c192c978f24
Matthiosso/snake-game
/snake/game/items/snake.py
950
3.796875
4
class Snake: def __init__(self, pos_x, pos_y, size=1): self.body = [[pos_x, pos_y]] self.size = size def head(self): return self.body[-1] def headx(self): return self.head()[0] def heady(self): return self.head()[1] def move(self, direction): if ...
d9a2b6c105a1362001a9b1903b38a68f38322ee5
MrHamdulay/csc3-capstone
/examples/data/Assignment_6/mclemi002/question2.py
655
3.53125
4
#emile mclennan #assignment 6 #Q2 import math vectA=input('Enter vector A:\n').split(" ") vectB=input('Enter vector B:\n').split(" ") a1 =eval(vectA[0]) #isolate values in array a2= eval(vectA[1]) a3= eval(vectA[2]) b1= eval(vectB[0]) b2= eval(vectB[1]) b3= eval(vectB[2]) calc1 = [a1+b1, a2+b2, a3+b3]...
cc3352a8cdd74c2c5fa903fdbf7308fe83300b87
abhilampard/SUDOKU-using-Backtracking
/sudoku_create.py
2,469
3.671875
4
import random sudoku=[[0 for i in range(9)] for j in range(9)] sudoku=[[1,2,3,4,5,6,7,8,9],[4,5,6,7,8,9,1,2,3],[7,8,9,1,2,3,4,5,6],[2,3,4,5,6,7,8,9,1],[5,6,7,8,9,1,2,3,4],[8,9,1,2,3,4,5,6,7],[3,4,5,6,7,8,9,1,2],[6,7,8,9,1,2,3,4,5],[9,1,2,3,4,5,6,7,8]] def disp(): for i in range(0,9): for j in range(0,9): if(su...
78bc18dab2c2c67d2cfe70e9a5431bbd5b1c9c89
aifulislam/Python_Demo_Five_Part
/program19.py
3,478
4.21875
4
#19/October/2020-------- #Python---Classes and Objeects---- #Iterators---------- print("Iterators-----------") mytuple = ("Apple", "banana", "cherry") myit = iter(mytuple) print(next(myit)) print(next(myit)) print(next(myit)) #Iterators--------- print("Iterators-----------") student = ("Arif","Tamim","...
701a8b5fac3a6021d7ac42aa800e18363a76a732
Nikhitha913/Datavisualization_ISM6419
/week8ass8-3.py
538
3.78125
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np import pandas as pd import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') Location = "datasets/gradedata.csv" df = pd.read_csv(Location) df.head() # In[9]: plt.scatter(df['hours'], df['grade'],color= 'red', alpha =...
c0b493e807568f3c7a84f00ba3aff49ffc3c7e8e
KaynRO/Teme-Poli
/IC/lab2/ex1.py
761
3.8125
4
from caesar import * def decrypt(ciphertext): for key in range(28): plaintext = '' for char in ciphertext: value = chr(ord(char) - key) if ord(value) < 65: value = chr(90 - (65 - ord(value)) + 1) plaintext +=value if "YOU" in plaintext: ...
f017615d033168fc9b9492791ddf20715d8e80e2
Jiezhi/myleetcode
/src/429-N-aryTreeLevelOrderTraversal.py
2,746
3.703125
4
#!/usr/bin/env python """ CREATED AT: 2021/8/6 Des: https://leetcode.com/problems/n-ary-tree-level-order-traversal/ https://leetcode.com/explore/challenge/card/august-leetcoding-challenge-2021/613/week-1-august-1st-august-7th/3871/ GITHUB: https://github.com/Jiezhi/myleetcode """ from typing import List from ntree_...
068b2ceee247c1790fdbdf9d3dc9464d58a30b36
shreyasabharwal/Data-Structures-and-Algorithms
/Trees/4.4CheckBalanced.py
1,242
4.1875
4
'''4.4 Check Balanced: Implement a function to check if a binary tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that the heights of the two subtrees of any node never differ by more than one. ''' import math from TreesBasicOperations import Node def checkHei...
77c31251013c0c5697f05d2b627799175f56c838
ayanez16/Tarea-1-Estructura
/Ejercicio6.py
500
3.5
4
#Dado el sueldo de un empleado, encontrar el nuevo sueldo si obtiene un aumento del 10% si su sueldo es inferior a $600, en caso contrario #no tendra aumento. class Ejercicio6: def __init__(self): pass def run(): suel = float(input("Ingrese el sueldo del empleado")) ...
16b0f7617bf462dc06661dacbbb06f3d402aea60
nitinjugal17/PythonPuzzle
/test.py
1,781
3.765625
4
# -*- coding: utf-8 -*- from random import randint import sys # getting 10000 digit number using randint rand_number = randint(10,9999**5630) #print 'Random String Type :',type(rand_number) #print 'Random String :',rand_number #checking for the size of randint #print 'Random String Length :',sys.getsizeof(rand_numb...
0b93ac1d2910f037beb008f87b731a41b2a07fec
CleverParty/containers
/algos/squareConvergents.py
1,022
3.96875
4
import sys from fractions import Fraction sys.setrecursionlimit(10000) a = 2 root = a**2 def convergent(num): base = 1 if num == 0: return False elif num > 1000 : return None num -= 1 sumCon = base +1/(1/2 + convergent(num)) # this just calculates the convergence recursively, for fu...
64119ca1ec4197d7ac4a4f95c3eb517876ef4e25
jiangbo721/test
/interview.py
1,672
3.953125
4
# -*- coding:utf-8 -*- # @project: test # @author: liujiangbo # @file: interview.py # @ide: PyCharm # @time: 2019-04-09 15:19 def SepPositiveNegative(test_list): """ 将数组里的负数排在数组的前面,正数排在数组的后面。但不改变原先负数和正数的排列顺序。 """ if len(test_list) <= 1: return test_list for _ in range(len(test_list)): ...
fe8383297dcb89e1ae938644dda3a47a6860cfbf
group6BCS1/BCS-2021
/src/chapter4/exercise6.py
509
4.0625
4
x = (input("enters hours")) y = (input("enters rate")) def compute_pay(hours, rate): """The try block ensures that the user enters a value between from 0-1 otherwise an error message pops up""" try: hours = float(x) rate = float(y) if hours <= 40: pay= float(hours * rate...
fc49880fbc716444c749b666f7245402442c8a14
paulocesarcsdev/ExerciciosPython
/2-EstruturaDeDecisao/9.py
1,118
4.40625
4
# Faça um Programa que leia três números e mostre-os em ordem decrescente. numeroUm = int(input('Numero um: ')) numeroDois = int(input('Numero dois: ')) numeroTres = int(input('Numero tres: ')) # Exibe o maior if(numeroUm > numeroDois and numeroUm > numeroTres): print("Numero um maior", numeroUm) if(numeroDois > ...
05a4a46e96103dba292866aba9831b4a7d57bbe9
Ensiss/snippets
/dailyprogrammer/180/Easy/looknsay.py
485
3.734375
4
import sys def lookNsay(s, n): if n <= 0: return s nstr = "" count = 0 prev = "\0" for c in s: if c != prev and count: nstr += str(count) + prev count = 0 count += 1 prev = c nstr += str(count) + prev return (lookNsay(nstr, n - 1)) if...
ef16fa6a312e71fdb5184f044beab2b78be0fac3
achillis2/Leetcode-1
/wip/base/mylist.py
946
3.8125
4
# 数组 li = [1, 2, 3] for i in li: print(i) for i in range(len(li)): print(li[i]) #append(self, object, /) li.append(4) #copy(self, /) ##相当于li2 = li[:] li2 = li.copy() #extend(self, iterable, /) ##前者合并可迭代对象 li2.extend(li) #index(self, value, start=0, stop=9223372036854775807, /) ##通过元素值查找元素下标(元素值,开始坐标=0,结束坐标=...
f6428de468ea366d08af27782302df49064f88d7
Arnav-17/Project-Euler-Codes
/Problem 19.py
1,763
3.515625
4
days = 0 a = 0 b = [] for year in range(1901, 2001): if year % 4 == 0: for month in range(1, 13): if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12: for date in range(1, 32): days += 1 ...
5f0a34b78f9de3cc93f2f375b63093c905d5e8c4
tejavarma-twl/python2
/loops.py
657
3.96875
4
a = 1 while a<=5: b = 1 while b<=5: print(b,end=" ") b += 1 a += 1 print("") a = 1 while a<=5: b = 1 while b<=5: print(a,end=" ") b += 1 a += 1 print("") a = 5 while a>=1: b = 1 while b<=a: print(b,end=" ") b += 1 a -= 1 pr...
8b9fa72e9480facc99108ab57a37c405f1b564c0
FrankieZhen/Lookoop
/Data Structures and Algorithm Analysis/Graph/toplogical_sort.py
1,590
3.8125
4
# 2018-8-21 # 拓扑排序 # 算法导论 P335 # 数据结构与算法分析 P219 class Vertex(object): def __init__(self, name=None, degree=None, p=[], c=[]): self.name = name self.degree = degree # 入度 self.p = None # 前驱 self.c = None self.sortNum = None def topSort(G): """ 使用BFS实现拓扑排序。 每次找到入度为0的节点放入列队,遍历与入度为0的点相邻的节点,并将度数减少1,如果度数变为0则...
6a2676c252fad4d7e915d7f94169de53dcc1c467
dahem/handbook
/uri/beginner/1117.py
233
3.71875
4
x = None while True: a = float(input()) if a < 0 or a > 10: print("nota invalida") continue if x == None: x = a continue else: print("media = %.2f" % ((a+x)*0.5)) break
50aec705d915b8b74411b80ca88f381f6718e224
nss-day-cohort-13/language-analyzer-lexi-con-artists
/sentiment.py
9,085
3.515625
4
from lexicon import * class Sentiment(Lexicon): ''' Classify a message into Sentiment subcategories ''' def __init__(self): ''' Call the Lexicon constructor with this lexicon's data ''' super().__init__('sentiment', sentiment_lexicon) def categorize_message(self,...
6efe5693066b42f3cb1c17435858664250bbaddb
DouglasAquino/Fractais-Geometricos
/Quadrado.py
742
3.515625
4
import turtle def drawSpiral(t, length, color): if length != 0: newcolor = (int(color[1:],16) + 2**20)%(2**24) newcolor = hex(newcolor)[2:] newcolor = "#"+("0"*(6-len(newcolor)))+newcolor t.color(newcolor) t.forward(length) t.left(90) drawS...
ece7c3258b84aaec7a0b383990536fdd24005ce6
gabidinica/PEP20G06
/modul6/modul6.py
3,412
3.84375
4
# iterators class ListIterator: def __init__(self, my_list: list): self.my_list = my_list def __next__(self): if len(self.my_list) == 0: raise StopIteration return self.my_list.pop(0) def __iter__(self): return self iterator = ListIterator([1, 2, 3]) for i i...
0ab93e622a8d2fee72075a42017e6bdb2f702463
OtherU/Python_Cursos_online
/desafio_028.py
592
3.71875
4
# ------ Modules ------ # from random import randrange # ------ Header & Footers ------ # header = str(' Desafio 028 ') subfooter = ('-'*68) footer = ('='*68) # ------ Header ------ # print('{:=^68}'.format(header)) # ------ Body ------ # n1c = int(randrange(5)) pler = str(input('Digite o nome do jogador: ')) n2p = ...
7772bfc196e455a5f555d6a7718272f97b70080e
carawaters/AstroImageProcess
/profile_gauss.py
1,474
3.59375
4
""" Creates a Gaussian profile and fits a Sersic profile to the intensity Author: Cara Waters Date: 15/12/20 """ import numpy as np import matplotlib.pyplot as plt from numpy import random from profile import int_radius, sersic_index, sersic def makeGaussian(amp, sigma, center): """ Makes a symmetric 2D gaussi...
78531b3bb399784b2bb12f7d348f69e4a7158b18
cravo123/LeetCode
/Algorithms/0783 Minimum Distance Between BST Nodes.py
1,164
3.640625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # Solution 1, recursion # DFS returns previous value class Solution: def dfs(self, node, prev_val): if node is None: return prev_val ...
729acb1426577060b0af61ec52194a2d437bc24b
DanielJHaar/Python_Practice_Jun2020
/Alphabet_Rangoni.py
613
3.78125
4
import string alphabet = list(string.ascii_lowercase) def print_rangoli(size): order = size - 1 for i in range (order, 0, -1): row = ['-'] * (2 * size - 1) for j in range(size - i): row[order - j] = row[order + j] = alphabet[j + i] print('-'.join(row)) ...
9f2210ce083407107bd1294da841fdcc445613ef
jacintojosh/advent-of-code-2020
/puzzle1/puzzle1.py
1,219
4.0625
4
f = open('input.txt', 'r') expense_report = [int(line.replace('\n', '')) for line in f] sorted_expense_report = sorted(expense_report) # Find the two entries that sum to 2020; what do you get if you multiply them together? def find_2_num_sum_2020_product(arr): j = len(arr) - 1 i = 0 found_sum = False while(j...
92bd9f43e5b4af5ee8448aa0a770fa9b6ffea00e
nikmalviya/Python
/Practical 8/remove_string.py
240
3.765625
4
filename = input('Enter Filename : ') string = input('Enter String you want to remove : ') file = open(filename, 'r') file_data = file.read() file.close() file = open(filename, 'w') file.write(file_data.replace(string, '')) file.close()
498d6c5079b143ecc57a5ad4ab2663701fcb70ee
Alexfordrop/Basics
/som_math.py
225
3.546875
4
import math radius = 30 # площадь круга с радиусом 30 area = math.pi * math.pow(radius, 2) print(area) # натуральный логарифм числа 10 number = math.log(10, math.e) print(number)
14822f0ef679b6762a00ed561fb1914ef701ea0c
wilkoklak/cTime
/example.py
346
3.78125
4
import cTime import time # A timer that will return a floating point number cTime.time('timer1', _round=5) # A timer that will print results itself to the console cTime.time('timer2', _print=True) time.sleep(10) cTime.timeEnd('timer2') time.sleep(5) print('Printed timer1: {}'.format(cTime.timeEnd('timer1'))) # See R...
2e632ec66a84f8a686941dc63f17a3609c2372b1
sphilmoon/karel
/diagnostic/new.py
351
4.3125
4
def main(): sequence_length = 1 intro() user_input = float(input("Enter num: ")) while user_input >= user_input: sequence_length += 1 user_input = float(input("Enter num: ")) if user_input < user_input: print("Thanks for playing!") def intro(): print("Enter a sequence of non-decreasing numbers.") if __n...
822e6592b12d01e409dcba0d1225029f0c13c74a
MrHamdulay/csc3-capstone
/examples/data/Assignment_2/wltaid001/question3.py
314
4.375
4
#Aiden Walton #WLTAID001 #Program to calculate area of circle given radius import math pi=2 den=math.sqrt(2) while den<2: pi=pi*(2/den) den=math.sqrt(2+den) print("Approximation of pi:",round(pi,3)) r=eval(input("Enter the radius:\n")) area=pi*r**2 print("Area:",round(area,3))
595008685003d521fe4ce96d96427ea0bc0a2633
tseddon84/neptune_pride
/battle_checker/battle_check.py
1,430
3.75
4
import math defender_fleet=eval(input("How many ships are in defender fleet? ")) attacker_fleet=eval(input("How many ships are in attacker fleet? ")) defender_weapons=eval(input("What is your defender weapons tech? ")) attacker_weapons=eval(input("What is your attacker weapons tech? ")) hours=eval(input("How many hours...
c76a88f3564c8cf17a5f1a0ee3c288572bbb93d9
Emerson53na/exercicios-python-3
/059 Criando um menu.py
1,134
3.640625
4
from os import system system('clear') go = False while True: v1 = int(input(' Digite o primeiro valor: ')) v2 = int(input(' Digite o segundo valor: ')) go = True while go == True: n = int(input('''\n [1]Somar [2]Multiplicar [3]Maior [4]Novos números [5]Sair do programa \...
9ba6e728c08fc5145c20f75d7c7b5557c1d4b0b6
lf832003/C-NMC_evaluation_code
/code/IO.py
426
3.5625
4
import os from natsort import natsorted def readfileslist(pathtofiles, fileext): if not os.path.exists(pathtofiles): raise Exception('Path does not exist!') lstFiles = [] for dirName, _, filelist in os.walk(pathtofiles): for filename in natsorted(filelist): if fileext in filen...
93637b0789f59a135c4416ded7fe389e5e841bca
mohitgite/TOC_ASS
/3.py
103
3.703125
4
m = int(input()) n = m.count("0") if n%3==0: print("Accepted") else: print("Rejected")
061f098fa97a7abd3b04dd4006472f481866eee8
piotrch-git/kurs_py
/dzień03/05_Slowniki.py
861
3.84375
4
#Słownik - nieuporządkowoana, mutowalna kolekcja par(klucz - wartość) - od pythona 3.coś gwarantowana jest kolejność zgodna z kolejnością wstawiania slownik = {} print(type(slownik)) stan_konta = {"Kowalski":120, "Nowak":15} print(stan_konta) print(stan_konta["Kowalski"]) print(type(stan_konta["Kowalski"])) #print(stan...
9a970eaf34797d251e6b26ca29e7ace9b7018854
raghavddps2/Technical-Interview-Prep-1
/BitManipulation/evenOdd.py
680
4.28125
4
""" Write a program to determine if the number is even or odd. Please don't use any modulus operator 0: 00000 1: 00001 2: 00010 3: 00011 4: 00100 5: 00101 6: 00110 7: 00111 8: 01000 9: 01001 -----> Looking at the above pattern we notice that if the least significant...
3e6ec4717874dfe8d57c3147d706be01e53917f5
bobby233/Pysysbeta
/Pyox.py
5,668
3.53125
4
# 名称:Pyox游戏 # GitHub上的作者:bobby233 # 一款OX棋游戏,内置于Pysys # 版本:0.0.1beta import random import Pysys_str as s import PSDK as p class Pyox(): """游戏主体""" def ask_diff(self): """询问难度""" while True: if s.oxout: break print('These are the difficulties:') ...
abe69741468621df2b18bd319de4a5c2cb234070
IsraMejia/Python100DaysOfCode
/D9-GradingProgram.py
761
4.1875
4
student_scores = { "Harry": 81, "Ron": 78, "Hermione": 99, "Draco": 74, "Neville": 62, } # 🚨 Don't change the code above 👆 print('\n\t Grading Program\n') #TODO-1: Create an empty dictionary called sudent_grades. sudent_grades = {} #TODO-2: Write your code below to add the grades to sudent_grades.👇 for s...
61bc59c1f763b8b7d96d87c3e72e337ab8610d04
zd6515843/super_chen
/PythonSelfStudy/Lession01-09/lession_09_Class.py
3,434
3.59375
4
class Dog(): def __init__(self, name, age): ''' 初始化属性name age ''' self.name = name self.age = age def sit(self): print(self.name.title() + " is now sitting.") def roll_over(self): print(self.name.title() + " rolled over.") my_dog = Dog('vis', 5) print('My dog na...
ef1cf9dd075ac2919e96e3f751f09c564001545f
NixonZ/PythonZ
/classes.py
472
4.09375
4
#learning classes class complex: """Implementing Complex numbers""" real=0 imag=0 def __init__(this,real=0,imag=0): this.real=real this.imag=imag def __str__(this): return (str(this.real)+'+'+str(this.imag)+'i') def update(this,x,y): this.real=x this.imag=...
dfc63dc906a0a3954d5e7ba0cd94a5a2dce5064b
mridubhatnagar/concepts-brushup
/functions/firstclassfunctions.py
456
4.25
4
""" Learning 1. Function can be passed as argument. 2. Returned from a function. 3. assigned to a variable. """ def square(x): return x*x #Passing function as argument def my_map(func, arg_list): result = [] for i in arg_list: result.append(func(i)) return result squares=my_map(square, [1,2,3,4,5]) print(squa...
dc37e762edb0d1d382a7f5142236fb71e871f5ee
oldmuster/Data_Structures_Practice
/hashmap/python/containsDuplicate.py
444
3.703125
4
#!/usr/bin/env python #coding:utf-8 """ 217. 存在重复元素 https://leetcode-cn.com/problems/contains-duplicate/ """ class Solution(object): def containsDuplicate(self, nums): """ :type nums: List[int] :rtype: bool """ num_dic = {} for i in nums: if i in num_...
36e8daf523a9b78d6cabf697e9e1b1c4e3a69b68
aten2001/CS7646-2
/tonumber.py
588
3.84375
4
#!/usr/bin/env python import sys, string """ tonumber.py < file.txt > file.number """ def convertStringToAsciiCharacters(sentence): ascii_rep=[] for word in sentence: for char in word: ascii_rep.append(ord(char)) return ascii_rep if len(sys.argv) < 2: sys.stderr.write('Usage: sys.a...
63b5c56c62186a9fbcb1694a6f415cbe967cdbd6
Uche-Clare/python-challenge-solutions
/Imaobong Tom/Phase 1/Python Basic 1/Day 3/5.py
161
4.46875
4
from math import pi r = float(input("Enter the radius of the sphere: ")) volume = 4/3 *(pi * r ** 3) print("The volume of the sphere is ", volume, end = " cm^3")
090df6bed7aa70d83844452d2051a26a73de8d57
jieshenboy/LeetCode
/code/fibonacci.py
741
3.9375
4
class Fibonacci(object): """ 返回一个斐波那契数列 """ def __init__(self): self.fList = [0,1] #设置初始列表 self.main() def main(self): listLen = input("请输入fibonacci数列的长度(3-50):") self.checkLen(listLen) while len(self.fList) < int(listLen): self.fList.append(self....
3ad59d6d7857a210767cd26df3db18b09c79bf27
MYMSSENDOG/leetcodes
/539. Invert Binary Tree.py
1,284
3.96875
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 from tree_node_lib import * class Solution: def invertTree(self, root: TreeNode) -> TreeNode: if not root or (not ro...
af571651636a510c0ee95cbbb3888f58b2f3d8ab
krolique/project_euler
/solutions/034_digit_factorials.py
659
4.09375
4
# -*- coding: utf-8 -*- """ Problem #34 - Digit factorials ------------------------------ 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. Find the sum of all numbers which are equal to the sum of the factorial of their digits. Note: as 1! = 1 and 2! = 2 are not sums they are n...
ccb5b6324a0279e277f7182f830525d049d03c5d
SimasRug/Learning_Python
/Chapter2/D1.py
181
3.703125
4
total = 0 temp = 1 for x in range(64): temp = temp * 2 total = total + temp # print(x, temp, total); total_weight = total/7000 print('total weight: ', total_weight)
b611365007feff03441dbd95f6091a1748f8ec33
adigeak/leetcode
/python/leetcode1.py
195
3.609375
4
def square(x): return x*x def map_fuc(fuc, arr): a = [] for i in arr: a.append(fuc(i)) return a x = [ i for i in range(1,6)] squares = map_fuc(square,x) print(squares)
7e74d14a819612a273378461958f8e2751083278
daniel-reich/ubiquitous-fiesta
/66xK46dhKFCe5REDg_16.py
1,401
3.96875
4
def x_and_o(board): def board_to_list(bo = board): e = [] #The 1 dimensional list that will house the other lists for a in range(3): #Just puts the board into a 2 dimensional lst l = board[a].split("|") e.append(l) return e def win(lst): #This function determines if a board is a win for X ...
07774c13515b4e671be1c128e3529e19e01f0020
juarezfrench/cs-module-project-recursive-sorting
/src/sorting/sorting.py
2,001
4.25
4
# TO-DO: complete the helper function below to merge 2 sorted arrays def merge(arrA, arrB): elements = len(arrA) + len(arrB) merged_arr = [0] * elements # Your code here def sort(a_index=0, b_index=0, index=0): if index >= len(merged_arr): return merged_arr else: ...
54139fc5991c4c760ea8bc8b79a7530781a4c6b1
msarfati/sqlalchemy-sandbox
/01engine.py
1,277
4.375
4
#!/usr/bin/env python # Michael Sarfati -- tutorial from Mike Bayer's Introduction to SQLAlchemy # ( https://www.youtube.com/watch?v=P141KRbxVKc ) # This script explores SQL alchemy's engine basics from lessonNice import printBorder as pb pb("01: SQLAlchemy - Engine Basics") #Actual tutorial begins here. For use with ...
b3c567bf469ca098942eed6d06d50bec1c3ebacb
SelmTalha/sinav_calisma
/VizeÇalışma(python)/Örnekler/format.py
122
3.8125
4
#Formatlama islemini yapiniz ! a=int(input("Bir sayi :")) b=int(input("Bir sayi :")) print("{} + {} = {}".format(a,b,a+b))
7fd7ec66a3f7aebb33b0386671332dd5b945e090
nataliegarate/python_ds
/lists/list_of_products.py
212
3.875
4
def findProduct(arr): products = [] product = 1 for x in arr: product *= x for num in arr: products.append(int(product/num)) return products print(findProduct([1, 2, 3, 4]))
7dee8ad7c8afcf16b70112335397e95eb072a79d
awillats/SkillsWorkshop2017
/Week01/Problem04/cbalusek_04.py
502
3.984375
4
""" Created on Fri Jul 21 11:20:45 2017 The goal of this program is to find the largest palindromic number formed by two three digit numbers It can be modified slightly to produce a list of palindromes and the integers that generate them. @author: cbalusek3 """ nList = range(999,900,-1) test = 0 i = 0 for n1 in nList:...
d1b25583246d2f16b3f47e65003ec56c7dd646a1
entcs/Moba
/rulez/rolls.py
440
3.578125
4
import math,random sides=20 dices=10 roll=0 r1=0 rolls=[0]*dices count=1000 for tnr in range(count): for nr in range(dices): roll=0 for nr1 in range(nr+1): r1=int(random.random()*sides)+1 if r1>roll: roll=r1 rolls[nr]+=roll want=5 sides=20 dices=5 fo...
bc7f4304b24f6d593524eeb391c60fc43caeb368
LXCuup/Pythoncode
/pizza_materials.py
219
3.6875
4
prompt = "Please add materials of your pizza:" prompt += "\n Enter 'quit' when you are finishend. " materials = " " while materials != 'quit': materials = raw_input(prompt) if materials != 'quit': print materials
2f020b0ac05bedc72cce5eefbbb6032f53801dc0
etherion-1337/Data_Structure_Algo_UCSD
/Course_1_Algorithmic_Toolbox/week2_algorithmic_warmup/1_fibonacci_number/fibonacci.py
745
3.890625
4
# Uses python3 def calc_fib(n): """ Slowest. Use Fibonacci definition """ if (n <= 1): return n return calc_fib(n - 1) + calc_fib(n - 2) def calc_fib_algo(n): """ Faster algo. Use human like algo to calculate """ if n <= 1: return n else: prev = 0 curr ...
6957c0246d4d087d53ddb179b73a4c67b611e6f9
bkalcho/python-crash-course
/cubes.py
192
3.8125
4
# Author: Bojan G. Kalicanin # Date: 28-Sep-2016 # Make a list of the first 10 cubes cubes = [] for value in range(1, 11): cube = value ** 3 cubes.append(cube) for cube in cubes: print(cube)
f2670121af366216a68c8050d7bd77bd28cdb4f9
danielfk11/calculadora
/main.py
3,446
3.875
4
from tkinter import * from typing import Match root = Tk() root.title("Calculadora") root.config(background='grey') e = Entry(root, width=35, borderwidth=5) e.grid(row=0, column=0, columnspan=3, padx=10, pady=10) #e.insert(0, "") # DEFINIR AS FUNCOES def button_click(number): current = e.get() ...
cb1ccf8e53e0ff30b1ffdb810bf33af1913f9a30
Fahmiady11/trapezoid-recrusive
/190411100127_muhammad fahmia ady susilo.py
534
3.984375
4
def rumus(x): return 1/(1+x**2) def trapezoid(x, y, z): integerasi = rumus(x)+rumus(y) h=(y-x)/z i=1 while i<z : integerasi = integerasi+(2*rumus(x+i*h)) i+=1 integerasi =integerasi * (h)/2 return integerasi print("RUMUS : 1/(1+x**2)") batasBawah = int(input("Masukkan batas b...
a15c7d53249a5f94dda3afc4bc215e80afb556c6
jasonim/learn-python3
/basic/my_list.py
271
3.71875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- people = ['Jason', 'xiaoming', 'Bob'] print(people, len(people)) print (people[-1]) # print people[-4] out of range people.insert(1, 'Jack') print(people) print(people.pop()) s = ['python', 'java', people, 'c'] print (s)
440fa96338349f1161e738b50862342c619b355f
iamanx17/dslearn
/Binary Tree/binarytree.py
580
3.703125
4
class Node: def __init__(self, data): self.data=data self.left=None self.right=None def takeinput(): data=int(input()) if data==-1: return root=Node(data) root.left=takeinput() root.right=takeinput() return root def printdata(root): if root is Non...
ab8709c5a3e889792c1ba8a26448a31085be6421
rramdin/adventofcode
/src/2017/advent2.py
1,976
3.78125
4
#!/usr/bin/python import sys import io # The spreadsheet consists of rows of apparently-random numbers. To make sure # the recovery process is on the right track, they need you to calculate the # spreadsheet's checksum. For each row, determine the difference between the # largest value and the smallest value; the che...
83e3bf146462ca5e1ae44ed841c57fb60d75499d
szhua/PythonLearn
/Unit2/Lesson15.py
2,065
4.09375
4
#Python的多线程: import threading ,time ,random #在子线程中进行轮询操作 def loop(): #显示当前线程的名字 print("current thread name: %s"%threading.current_thread().name) n = 0 while n<5: print("thread %s ==> %s"%(threading.current_thread().name,n)) n+=1 time.sleep(1) print("child thread ...
05fded1c54d25cdae5ec7b85fad3a7a2cd3259b1
ypliu/leetcode-python
/src/126_word_ladder_ii/126_word_ladder_ii_BiBfs.py
1,624
3.59375
4
from collections import defaultdict import string class Solution: def findLadders(self, beginWord, endWord, wordList): """ :type beginWord: str :type endWord: str :type wordList: List[str] :rtype: List[List[str]] """ if endWord not in wordList or not endWord o...
320368cbefe509de819e26fe97ed004993d7d266
llraphael/algorithm_problems
/array/FindAllDuplicatesInArray.py
1,005
4.0625
4
""" Find all the duplicates in an array. Since 1 <= a[i] <= n and n is the length of the array, if there is no duplicate, the array should contain every number from 1 to n and we can make the correspondance between the value and its place in the array as (val, val - 1). Thus, the general idea is to check each element ...
cdf4ce0acf4af7d19d4e75f7645fd44c970b008b
JaeyoonChun/git-practice
/WhatDate.py
1,670
3.828125
4
def input_date(): year = int(input("__년도를 입력하시오:")) month = int(input("__월을 입력하시오:")) day = int(input("__일을 입력하시오:")) return year, month, day def get_day_name(input_year, input_month, input_day): day_sum = 0 monthly_numOfDay=(31,28,31,30,31,30,31,31,30,31,30,31) day_name=("일요일","월요일","화요일",...
5952eef87814a720ee631230498c14e53bf07d02
marchon/nanoservice
/nanoservice/config.py
1,515
3.5
4
""" Read configuration for a service from a json file """ import io import re import json from .client import Client class DotDict(dict): """ Access a dictionary like an object """ def __getattr__(self, key): return self[key] def __setattr__(self, key, value): self[key] = value def l...
69f79fabfc885ded53fdcf434e5bca5335cec0df
infinitepassion/Simulations
/Projects/Shell Project/cmd_pkg/mv.py
462
3.71875
4
import sys import os import shutil """ @Name: mv @Description: Used to rename a file @Params: cmd(list) - the file to rename """ def mv(cmd): os.system('touch output.txt') if len(cmd)==3: if os.path.isfile(cmd[1]): # copy the file and then remove original file shutil.copyfile(cmd[1], cmd[2]) os.remove(cmd[...
857695d8e23d23d8713ef8325316501250e621a1
BjornChrisnach/Python_6hour_course
/Intermediate/map_function.py
241
3.6875
4
# map function nr3 li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def func(x): return x**x # newList = [] # for x in li: # newList.append(func(x)) # print(newList) # print(list(map(func, li))) print([func(x) for x in li if x % 2 == 0])
da7f4b62871ce3351c9da3e7590f73b293a81a42
fabiannoda/PythonTutorial
/Sintaxis Basica/excepciones2.py
868
4
4
''' def divide(): try: op1=float(input()) op2=float(input()) print(str(op1/op2)) except ValueError: print("Es bobo o que") except ZeroDivisionError: print("Es bobo o solo se hace") finally: print("se hizo") divide() ''' ''' def evaluaEdad(edad): ...
e986c5ff8f039aeb792866991d380fc9844e24fe
zil93rus/Python_lessons_basic-master
/lesson01/home_work/hw01_easy.py
2,012
4.15625
4
__author__ = 'Ваши Ф.И.О.' # Задача-1: Дано произвольное целое число (число заранее неизвестно). # Вывести поочередно цифры исходного числа (порядок вывода цифр неважен). # Подсказки: # * постарайтесь решить задачу с применением арифметики и цикла while; # * при желании решите задачу с применением цикла for. import ...
d126ffd0cc7300caa6e505fd741cdc8d118c8021
optionalg/programming-introduction
/Aula 09/Aula9-Extra-6.py
447
3.671875
4
""" Aula 9 Exercícios Extras 6 Autor: Lucien Constantino """ def get_number(): while True: number = int(input("Digite um número: ")) if number < 0: print("Número inválido") else: return number n = get_number() count = 0 number_count = 10 while count < n: li...
8d397c054ed70fe040b5cc3d376f254f15a9a78a
zaidajani/Hacktoberfest_2021-1
/Data Ekstrakulikuler.py
1,486
3.96875
4
#Cetak judul program (OUTPUT) print("---------------DAFTAR EKSTRAKULIKULER SMPN 1 CITEUREUP---------------") ekstrakulikuler = ["1.Pramuka","2.Paskibra","3.PMR", "4.Futsal", "5.Volly", "6.Tata boga", "7.Vokal"] print("Ada apa saja? seperti :") for eks in ekstrakulikuler: print (eks) #Mencetak output dengan ...
18b79befee42bc43967b760c53874beae9bbda09
Taeg92/Problem_solving
/Programmers/Level2/프린터/프린터.py
700
3.609375
4
def solution(priorities, location): answer = 0 val = priorities[location] priorities[location] = 0 while priorities: temp = priorities.pop(0) if priorities: if temp == 0: if val >= max(priorities): answer += 1 return ...
ed5f7816d9c97f2bf3d77416aa5043e7db80dac8
AdamRajoBenson/Rajo-
/binstr.py
112
3.671875
4
w=input() y=0 for i in w: if((i=='0')or(i=='1')): y=y+1 if(y==len(w)): print("yes") else: print("no")
6fd6d12905167467c27fdd2cfb2eeff1ffa92edd
robbyvan/-
/配列/35_Search Insert Position.py
418
3.515625
4
# 35. Search Insert Position # 类似34, 这里high取len(nums), 因为只用访问nums[mid]. # 如果mid >= target, 更新high, 否则更新low class Solution: def searchInsert(self, nums, target): if not nums: return 0 low, high = 0, len(nums) while low < high: mid = low + (high - low) / 2 if nums[mid] >= target: ...
6949c4adbb6b15d95df094e5892c7976b66e09ce
dyf102/LC-daily
/dp/python/shortest-path-visiting-all-nodes.py
1,070
3.984375
4
from collections import defaultdict, deque from typing import List def shortestPathLength(graph: List[List[int]]) -> int: """LC 847 Time complexity: O(N*2^N) Space: O(N*2^N) A pure BFS solution. It uses bit covery to store the status. Args: graph (List[List[int]]): [description] Return...
d4fd1a12e587680c804d21c6f5afbebb2bc5e58c
gourik/Machine-Learning-
/list_comprehension.py
757
4.375
4
# -*- coding: utf-8 -*- """ Created on Tue May 25 11:46:14 2021 @author: Gouri """ #List comprehension provides a concise way to create lists. It contains brackects which consist of # an expression followed by a for clause, then zero or more for or if clauses. The expressions can be # anything i.e we can a...
e10dccdebccbd050c2016605bf26239ad633a45d
annasedlar/algorithms_practice
/sum_of_digits_of_giant_exponents.py
268
3.921875
4
# 2^15 = 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? x = 2**1000 print x; y = str(x); print type(y); # print len(y); sum_digits = 0; for digits in y: sum_digits += int(digits); print sum_digits;
459218992665d84ac185404dcda0f1087677c16d
pizza2u/Python
/exemplos_basicos/python/basico_e_if.py
789
3.96875
4
nome = input("Seu nome: ") #-> input serve para pegar o dado escrito pelo usuário idade = int(input("Sua idade por favor: ")) curso = input ("Escreva seu curso: ") if idade > 30: #-> segue a mesma lógica de c e c++ : condição SE print("Você é velho") elif idade < 20 : print("Não tao novo") elif idade < 16: ...
f0b4a5f0b3e9f9fb2c644273ca4de44807625aab
Delictum/diploma-training
/3 course/Program design and programming languages/Python/LR3(1).py
1,828
4.25
4
import math ''' # {pow(x, 2) * log10(x), 1 <= x <= 2 # y ={1, x < 1 # {pow(e, 2 * x) * cos(5) * x, x > 2 print('Задание 1.') x = float(input('Введите x: ')) if (x < 1): y = 1 elif (x > 2): y = math.pow(math.e, 2 * x) * math.cos(5) * x else: y = pow(x, 2) * math.log10(x) print('y = ', y) #Написать пр...
7a598bcfc5fe8451058c145b3eedc2cd2ea532c9
AkashPatel18/Basic
/video 6.2/Q3.py
276
3.96875
4
def factorial(n): if n ==0: print("1") elif n<0: print("fact is not posibble") if n == 1: return n else: return n*factorial(n-1) n = int(input()) if n ==0: print("1") elif n<0: print("np") print(factorial(n))
cd5ce443a78a0eef6897412970e2a9768150f2b6
Zhanar24/AWS
/Python Class/.idea/Python Class_OOP-ATM.py
3,639
3.890625
4
# class ATM: # bal = 250 #bonus # lim = 500 # def __init__(self, balance): # #Attribute # #self.bal = balance # self.bal += balance # # print("This is your balance: {}".format(balance)) # print("Your balance is : {}".format(balance)) # # Getter method - ...
f4f96548f0eb74e6904ce8b81b01a2a9c99c2386
vkuberan/100-days-of-code-source
/day-6/python/arra-of-odd-rows-even-columns.py
285
3.796875
4
import numpy sampleArray = numpy.array([[3 ,6, 9, 12], [15 ,18, 21, 24], [27 ,30, 33, 36], [39 ,42, 45, 48], [51 ,54, 57, 60]]) print("Printing Input Array") print(sampleArray) print("\n Printing array of odd rows and even columns") newArray = sampleArray[::2, 1::2] print(newArray)