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
0fb68f202520e3370e544f8b7d53a2ad0ad69c42
Anupam-dagar/Work-with-Python
/Very Basic/factorial.py
228
4.1875
4
#calculate factoial of a number def factorial(x): result = 1 for i in range(1,x+1): result = result * i return result number = int(raw_input("enter a number:")) answer = factorial(number) print answer
b8311152abdc2a3e297147604b442772374c0252
bssrdev/Project
/mindstorms.py
1,635
3.984375
4
import turtle def draw_shapes(): window = turtle.Screen() window.bgcolor("green") #draw_square() #draw_circle() #draw_triangle() #draw_art() draw_flower() window.exitonclick() def draw_rhombus(some_turtle): for i in range(1,3): some_turtle.forward(100) some_turtle....
a61453a66571d1a00bb8970bd8d926e5a193925c
lugnitdgp/avskr2.0
/ve/Lib/site-packages/pyprint/ContextManagers.py
913
3.65625
4
# -*- coding: utf-8 -*- from contextlib import contextmanager, closing from io import StringIO import sys @contextmanager def replace_stdout(replacement): """ Replaces stdout with the replacement, yields back to the caller and then reverts everything back. :param replacement: A file IO object to repl...
fb067a66d72ae73131adf2dc34c0ce568ab87cad
kushagraagarwal19/PythonHomeworks
/HW2/5.py
876
4.15625
4
johnDays = int(input("Please enter the number of days John has worked")) johnHours = int(input("Please enter the number of hours John has worked")) johnMinutes = int(input("Please enter the number of minutes John has worked")) billDays = int(input("Please enter the number of days bill has worked")) billHours = int(inp...
ce9d121c3944e6183420f9e8539d24996185a3ec
Navya140311/Password.py
/password.py
1,150
3.9375
4
from tkinter import* import random root=Tk() root.title("Password Generator") root.geometry("500x500") label_password=Label(root) label_guessed_password=Label(root) input_1= Entry(root) array_3d=[[[1,2,3,4,5,6],["King","Queen"],["&","$","@","#","!","~",";",":"]]] def new_password(): value= input_1...
1b6c00090e3e5b2e458f5c236f80293efae5749e
JoranCourtens/5WWIPython
/07b-Whilelus/Rad van fortuin.py
359
3.875
4
#invoer woord = input('Geef woord: ') geldbedrag = int(input('Geef geldbedrag: ')) gewonnen_bedrag = 0 gegokte_letters = '' letter = input('Geef letter: ') #berekening while letter in woord and not letter in gegokte_letters: gegokte_letters += letter gewonnen_bedrag += geldbedrag letter = input('Geef lette...
569b474d90ae1469042f0c68f349cbceea82c277
gtadeus/LeetCodeChallenge2009
/week01/day05.py
912
3.53125
4
import collections class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def ret_vals(self): ret_list = [] for v in [self.val, self.left, self.right]: if (not v is None): if (not...
e4eb827cc4698bc915df9ad06de7e4e6a2d42035
lyoshida/Academia-Python
/calculadora.py
2,454
3.546875
4
# encoding: utf-8 """ Testes >>> calc = RPN() >>> calc.enter(5) >>> calc.visor() 5.0 >>> calc.pilha() [5.0] >>> calc.enter(10) >>> calc.pilha() [5.0, 10.0] >>> calc.enter('+') 15.0 >>> calc.visor() 15.0 >>> calc.pilha() [15.0] >>> calc.enter...
eaceb72ec4d33901a8043e4643b0c820afecc04e
Erick-Faster/Detector-Textos
/DetectorTextos v2.py
2,662
3.59375
4
# -*- coding: utf-8 -*- """ Created on Tue Aug 13 03:34:52 2019 Um texto eh introduzido em texto[] Palavras novas serao inseridas em analise[] Palavras conhecidas em dicionario[] @author: Faster-PC """ import shelve, os #Realiza a busca pela palavra no dicionario def busca(texto,i, dicionario): ...
ba3aebabdfecce63895245d38137180cdc007745
felippesantos00/Project-from-University
/ex02-15.py
552
3.71875
4
""" Exercicio 15:Escreva um programa para calcular a redução do tempo de vida de um fumante. Pergunte a quantidade de cigarros fumados por dia e quantos anos ela já fumou. Considere que um fumante perde 10 minutos de vida a cada cigarro e calcule quantos dias de vida um fumante perderá. Exiba o total em dias. """ ...
f091f0b0ccc218afdc6cffeecfd7ea6275a2d30b
taesookim0412/PythonAlgorithmsFocused1
/dynamic_programming/06_5_longest_palindromic_substring.py
573
3.6875
4
def longestPalindrome(self, s): dp = [[0] * len(s) for _ in range(len(s))] t = "" for i in range(len(s)): dp[i][i] = 1 t = s[i] for i in range(len(s) - 1, -1, -1): for j in range(i + 1, len(s)): if s[i] == s[j] and (j - i == 1 or dp[i + 1][j - 1] == 1): ...
164a5f5e3e433ac42630a240a76c83134a50642b
taesookim0412/PythonAlgorithmsFocused1
/twopointers/01_twosum_sortedd.py
497
3.78125
4
from typing import List def two_sum_sorted(arr: List[int], target: int) -> List[int]: l, r = 0, len(arr) -1 while l < r: total = arr[l] + arr[r] if total > target: r -= 1 elif total < target: l += 1 elif total == target: return [l, r] retu...
bb441360b68fd2b88eeee57b4cfc1bdd0a4e83ed
taesookim0412/PythonAlgorithmsFocused1
/arrays_and_strings/01_283_Move Zeroes.py
319
3.5625
4
from typing import List def moveZeroes(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ zeroPtr = 0 for i in range(len(nums)): if nums[i] != 0: nums[i], nums[zeroPtr] = nums[zeroPtr], nums[i] zeroPtr += 1 return nums
08ba7e2252f555b310a31d800cbe34cf1f57e5d7
taesookim0412/PythonAlgorithmsFocused1
/dynamic_programming/09_55_jump_game_1.py
505
3.5625
4
from typing import List #recursive, not one pass (refer to javascript) class Solution: def canJump(self, nums: List[int]) -> bool: return self.helper(nums, nums[0], 0) def helper(self, nums, currentNum, idx): if idx >= len(nums) - 1: return True for i in range(currentNum):...
7cc6ea6d5c7ad9edd9da9c38140eb82df3943955
taesookim0412/PythonAlgorithmsFocused1
/arrays_and_strings/04_20_valid_parentheses.py
532
3.59375
4
class Solution: def isValid(self, s: str) -> bool: stack = [] open_brackets = {0:'(', 1:'{', 2:'['} closed_brackets = {')':0, '}':1, ']':2} for ch in s: #if opener if ch not in closed_brackets: stack.append(ch) #if closer ...
2b63ec3b4582beb8a55b0b44a2074ee1a8c444b2
alaminbhuyan/Python-solve
/problem/list3.py
583
3.546875
4
lis = [] condition1 = "insert" condition2 = "append" condition3 = "pop" condition4 = "sort" condition5 = "print" condition6 = "reverse" condition7 = "remove" n = int(input()) for i in range(n): l = input().split() if l[0]==condition1: lis.insert(int(l[1]),int(l[2])) elif l[0]==condition2: l...
fa76386dcdffa9a545635ebf5c38f90d407b1ef8
alaminbhuyan/Python-solve
/problem/Shape_&_Reshape_array.py
158
3.59375
4
from numpy import * # arry = array([1,2,3,4,5,6]) # arry.shape=(2,3) # print(arry) arr2 = array(list(map(int,input().split()[:9]))) print(arr2.reshape(3,3))
200e529f8f5c8d35758263c382cb995d8e467399
alaminbhuyan/Python-solve
/problem/Map&Lambda.py
459
4.125
4
# # n = int(input()) # # def fibonacci(num): # lis = [0,1] # for i in range(2,num): # lis.append(lis[i-2]+lis[i-1]) # return (lis[0:num]) # x = fibonacci(n) # print(list(map(lambda x: pow(x,3),x))) def fibonacci(num): lis = [0,1] for i in range(2,num): lis.append(lis[i-2]+lis[i-1]) ...
5fdf95e7f2372e96e683e734a9434b3f029fa79b
alaminbhuyan/Python-solve
/problem/itertools3.py
374
3.59375
4
from itertools import combinations # string , value = input().upper().split() # string = sorted(string) # value= int(value) # lis = list(combinations(string,value)) # print(lis) # #lis.sort() # # for i in lis: # print(i,end='') string , value = input().split() for i in range(1, int(value)+1): for j in combi...
b82b5dee8738c26ce8ca0fae995c7119213540d4
alaminbhuyan/Python-solve
/problem/collection_namedtuple.py
607
3.828125
4
from collections import namedtuple # N = int(input()) # fields = input().split() # total = 0 # for i in range(N): # students = namedtuple('Student',fields) # field1, field2, field3,field4 = input().split() # student = students(field1,field2,field3,field4) # total += int(student.MARKS) # print('{:.2f}'....
2ac40da08ab20958703d45bc6114300b6c1be9d3
alaminbhuyan/Python-solve
/problem/itertools.py
291
3.546875
4
# a = list(map(int,input().split())) # b= list(map(int,input().split())) # # lis = tuple((x,y) for x in a for y in b) # print(lis) from itertools import product a = list(map(int,input().split())) b = list(map(int,input().split())) lis=list(product(a,b)) for i in lis: print(i,end=' ')
df23c42f672c812f81c6f10ee3558bce3f51946c
BarnaTB/Level-Up
/user_model.py
2,023
4.28125
4
import re class User: """ This class creates a user instance upon sign up of a user, validates their email and password, combines their first and last names then returns the appropriate message for each case. """ def __init__(self, first_name, last_name, phone_number, email, password): ...
273300f98953532953bc3b65179a7e6e562b4b40
Willco9455/dogWalker
/database.py
18,947
3.90625
4
## imports the sqlite3 functionality which allows you to create and query local databases import sqlite3 from flask import url_for '''Database Sturcture: user(userID(PK), username, password) ''' ## This the calss for the databse object that will be imported and used in the main appliation class dbClass: ## fun...
3ffacbe3eb4730e903185e871f2c9c2f183cb2a5
vrushalideo/Python_Code_Examples
/planning_a_vacation.py
799
3.84375
4
def hotel_cost(nights): return(140 * nights) def plane_ride_cost(city): if city == "Charlotte": cost = 183 return (cost) if city == "Tampa": cost = 220 return (cost) if city == "Pittsburgh": cost = 222 return (cost) if city == "Los Angeles": co...
d5a2414bc8d3e3fb711cc0c43fac1122173d4388
mitchellroe/exercises-for-programmers
/python/02-counting-the-number-of-characters/count.py
381
4.3125
4
#!/usr/bin/env python3 """ Prompt for an input string and print the number of characters """ def main(): """ Prompt for an input string and print the number of characters """ my_string = input("What is the input string? ") num_of_chars = len(my_string) print(my_string + " has " + str(num_of_cha...
6bd8bad393b43f64bd07bfc3682e13955b48f644
mamontinnokent/Project
/PYTHON/clc.py
858
3.609375
4
def clc(string): assert type(string) == str if string.find('+') != -1: strings = string.split('+') return int(strings[0]) + int(strings[1]) elif string.find('**') != -1: strings = string.split('**') if len(strings) == 2 and len(strings[1]) != 0: return int(string...
09ec4149adb4331b90d44753ff5013322db53384
azarafath/DASPRO_COVID-19
/Covid-19.py
4,102
3.5625
4
#PROGRAM DETEKSI COVID-19 ONLINE #UTS DASAR PEMOGRAMAN IK-1E #AHMAD ZAKARIA FATHONI _ 3.34.20.4.01 from IPython.display import clear_output def cls() : clear_output(True) while True: soal = ["Apakah kamu pernah melakukan test usap tenggorok atau hidung dengan RT-PCR dengan hasil positif ?", "A...
c4d72f57785d76503461fc2e574accd31fe8bdc7
pedrolisboaa/curso_python
/1_python_basico/14-documentacao.py
344
4.0625
4
num1 = input('Digite um Número: ') num2 = input('Digite um outro número: ') """ # isnumeric isdigit isdecimal # checa se existe somente números e positivos print(num1.isnumeric()) print(num2.isnumeric()) """ if num1.isdigit() and num2.isdigit(): print(int(num1) + int(num2)) else: print('Você di...
ba95d6e237015ab4898681b2561430a459efe9ba
pedrolisboaa/curso_python
/1_python_basico/16-2-atividade.py
340
3.890625
4
hora = input('Informe que horas são? ') if hora.isdigit() and int(hora): hora = float(hora) if 0 < hora > 24: print('Hora invalida') elif 5 <= hora < 12: print('bom dia') elif 12 <= hora < 18: print('boa tarde') else: print('boa noite') else: print...
9dfd1be574c76c30352296c62a5f754fce82ef8d
pedrolisboaa/curso_python
/1_python_basico/10-ifElifElse.py
213
3.9375
4
""" Condições if elif else """ cor = 'purple' if cor == 'green': print('É RGB') elif cor == 'red': print('É RGB') elif cor == 'blue': print('É RGB') else: print('Não é RGB')
3e491cacc1bc9db47a3799e2e256c6d345731a5e
siraiwaqarali/Python-Learning
/Chapter-17/3. Error raise example 1.py
642
4.09375
4
# raise errors example 1 # NotImplementedError # abstract method class Animal: def __init__(self, name): self.name = name def sound(self): raise NotImplementedError('you have to define this method in subclasses') class Dog(Animal): def __init__(self, name, breed): sup...
59af2128b9e6d314ca90fa7cd770f0f1f4278030
siraiwaqarali/Python-Learning
/Chapter-02/UserInput.py
297
4.15625
4
# To take input from user we use input() function name = input("Enter your name: ") print("Hello "+name) # input(Always takes input as a string) age=input("Enter your age: ") # This age is in String print("Your age is "+age) # Agr age int mn huta tou ye concatenate ni huta
bffff44fe4c1e78b5dab127314fe58d00e8b1fab
siraiwaqarali/Python-Learning
/Chapter-14/10. Decorators with Arguments.py
594
3.59375
4
from functools import wraps def only_data_type_allow(data_type): def decorator(function): @wraps(function) def wrapper(*args, **kwargs): if all([ type(arg)==data_type for arg in args ]): return function(*args, **kwargs) return 'Invalid Arguments!' ...
eb7021c42614f22df99ab1cc75a4c12e0c218df6
siraiwaqarali/Python-Learning
/Chapter-13/6. Zip Function Part2.py
343
3.90625
4
# We will do reverse in part2 # l1 = [1, 3, 5, 7] # l2 = [2, 4, 6, 8] l = [(1,2), (3,4), (5,6), (7,8)] # * operator with zip l1, l2 = list(zip(*l)) print(l1) # tuple print(l2) # tuple l1 = list(l1) l2 = list(l2) new_list = [] for pair in zip(l1,l2): new_list.append(max(pa...
5d9192fb3a7f91af57e796ab3325891af0c2cabe
siraiwaqarali/Python-Learning
/Chapter-05/10. More About Lists.py
582
4.15625
4
# generate list with range function # index method generated_list = list(range(1, 11)) print(generated_list) # output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 3] print(numbers.index(3)) # gives the index of the provided element print(numb...
bce98ae66c01b7c598c8610baa89c9f4dae28b27
siraiwaqarali/Python-Learning
/Chapter-07/3. Add and delete data from dictionaries.py
784
3.8125
4
user_info = { 'name': 'Waqar', 'age': 20, 'fav_movies': ['Dummy Movie 1', 'Dummy Movie 2', 'Dummy Movie 3'], 'fav_tunes': ['Dummy Tune 1', 'Dummy Tune 2'], } # how to add data user_info['fav_songs'] = ['Song1', 'Song2'] print(user_info) # pop method - deletes a key:value pair from dictionar...
9e0d8659be7a01bfaccc5d978b4b495e571491a1
siraiwaqarali/Python-Learning
/Chapter-03/ForLoopExample1.py
405
4.125
4
# sum of first ten natural numbers total=0 for i in range(1,11): # for sum of 20 numbers range(1,21) total+=i print(f"Sum of first ten natural numbers is {total}") # Sum of n natural numbers n=input("Enter the number: ") n=int(n) total=0 for i in range(1,n+1): # Second argument is excluded so to reach...
bf1c0a0d7e98d1d89ff053e71fdd374152848ae6
siraiwaqarali/Python-Learning
/Chapter-01/PythonCalculations.py
758
4.375
4
print(2+3) print(2-3) print(2*3) print(2/4) # This gives answer in fraction print(4/2) # This gives 2.0 print(4//2) # This gives 2 beacuse it is integer division print(2//4) # This gives 0 beacuse it is integer division print(11//3) # This gives 3 beacuse it is integer division print(6%2) ...
9ebdd87c5067140b6e3d5af41a58569552b85a11
siraiwaqarali/Python-Learning
/Chapter-16/Exercise3.py
652
4.15625
4
''' Exercise#03: Create any class and count no. of objects created for that class ''' class Person: count_instance = 0 def __init__(self, first_name, last_name, age): self.first_name = first_name self.last_name = last_name self.age = age # Increment count_instance ea...
01fa9082ef45132e18e8db69a9e00b278d4f0167
siraiwaqarali/Python-Learning
/Chapter-16/14. Special magic(dunder) method, operator overloading, polymorphism.py
1,858
4.21875
4
# Special magic/dunder methods # operator overloading # polymorphism - kisi cheez ki ek se zyada forms - one example is method overriding class Phone: def __init__(self, brand, model, price): self.brand = brand self.model = model self.price = price def phone_name(self): ...
b27811c71aa77b16e6b928bc280954f4c3fc7c58
siraiwaqarali/Python-Learning
/Chapter-15/4. List vs Generators.py
481
3.875
4
# List vs Generator # Memory Usage, Time # When to use list, when to use generator import time t1 = time.time() # l = [ i**2 for i in range(10000000) ] g = ( i**2 for i in range(10000000) ) print(time.time() - t1) # Pehle ek ko comment kro or check kro task manager mn memory or console mn time phr dsre ko...
d1ecd5f71b352f254142854248f00f9188a11718
siraiwaqarali/Python-Learning
/Chapter-05/6. is vs equals.py
392
4.15625
4
# compare lists # ==, is # == check values inside list # is checks address inside memory fruits1 = ['orange', 'apple', 'pear'] fruits2 = ['banana', 'kiwi', 'apple'] fruits3 = ['orange', 'apple', 'pear'] print(fruits1==fruits2) # False print(fruits1==fruits3) ...
d018f7a650bf973568edeb36cd962e37f2242311
siraiwaqarali/Python-Learning
/Chapter-03/Exercise1AndNestedif-else.py
273
4.0625
4
winning_number = 27 user_input = input("Guess a number between 1 and 100: ") user_input = int(user_input) if user_input==winning_number: print("You won!!") else: if user_input<winning_number: print("Too low") else: print("Too high")
7442dc58e10413a4535a8cbd98598ec2c4245658
siraiwaqarali/Python-Learning
/Chapter-16/12. Multilevel Inheritance, MRO, Method Overriding.py
3,409
4.21875
4
# Can we derive more than one class from base class ? Yes, we can # Multilevel Inheritance # Method Resolution Order # Method Overriding # isinstance(), issubclass() class Phone: # Base class / Parent class def __init__(self, brand, model_name, price): ...
7842cc576e5fb996cd3e7a17111bc36f86ed287a
siraiwaqarali/Python-Learning
/Chapter-16/10. Property and Setter Decorator.py
2,127
3.921875
4
# will discuss three problems in existing # then we will solve them using getter, setter decorator # class Phone: # def __init__(self, brand, model_name, price): # self.brand = brand # self.model_name = model_name # self._price = price # self.complete_specification = f'{self...
b7ddc0c4dd14fab70ca5d219241bd14ad18dbd7c
siraiwaqarali/Python-Learning
/Chapter-04/fibonacci_series.py
513
4.09375
4
# Fibonacci Series: 0 1 1 2 3 5 8 13 21 34 ... def print_fibonacci_series(n): a = 0 # first number b = 1 # second number if n==1: print(a) elif n==2: print(a, b) # a b -> 0 1 else: print(a,b, end=' ') ...
d351fdf978fde1ea7045c7681b8afe871e25d6d4
siraiwaqarali/Python-Learning
/Chapter-09/4. Nested List Comprehension.py
388
4.4375
4
example = [[1, 2, 3], [1, 2, 3], [1, 2, 3]] # Create a list same as above using nested list comprehension # new_list = [] # for j in range(3): # new_list.append([1, 2, 3]) # print(new_list) # nested_comp = [ [1, 2, 3] for i in range(3)] # but also generate nested list using list comprehension nested_com...
41157c73d86c95a4cdf5830981abb6bb652b18ba
siraiwaqarali/Python-Learning
/Chapter-07/2. Looping and in keyword in dictionary.py
1,307
3.9375
4
user_info = { 'name': 'Waqar', 'age': 20, 'fav_movies': ['Dummy Movie 1', 'Dummy Movie 2', 'Dummy Movie 3'], 'fav_tunes': ['Dummy Tune 1', 'Dummy Tune 2'], } # values method user_info_values = user_info.values() print(user_info_values) print(type(user_info_values)) # keys method user_info...
34b5bbfbf050c3d35eb2e35c005a836091f49b07
siraiwaqarali/Python-Learning
/Chapter-02/StringConcatenation.py
545
4.21875
4
first_name="Waqar" last_name="Siyal" full_name=first_name+last_name print(full_name) first_name="Waqar" last_name="Siyal" full_name=first_name + " " +last_name print(full_name) #String ke sath kisi number ko add ni kr skte string mn srf string ko add kr skte hain #print(first_name+3) This will give error ...
e4ca3edda19ce73a875e890dcfdb832e3b9ae62f
siraiwaqarali/Python-Learning
/Chapter-02/StepArgument.py
585
4.21875
4
#Syntax: [start argument:stop argument:step argument] print("Waqar"[1:3]) #Step argument yani jitna step dengy utna step agy lekr chlega print("Waqar"[0:5:1]) #ek ka step lega koi frk ni prega q wese bi next word he ayega print("Waqar"[0:5:2]) #ab do ka step lega print("Computer"[0::2]) print("Waqar"[0::3]) #...
7a925523f64602495b953a4b11d9ff5a02819164
WDrewMorton/SeaRPG
/Map.py
3,761
3.78125
4
import random class Map: map_list = [] coords = {} def __init__(self, difficulty=0, floor=0, sunken_door=False): self.difficulty = difficulty self.sunken_door = sunken_door self.floor = floor self.mob_nums = 5 * difficulty + random.randint(1, 5) # self.create_map(...
fd1194dd851649bad45fe19f1a3012be903aa5e1
dingelsz/Hausdorff-Dimension-Research
/earthworm.py
16,020
3.640625
4
import argparse from random import randint, seed import math from PIL import Image import csv BLACK = (0, 0, 0) GREY = (155, 155, 155) WHITE = (255, 255, 255) RED = (255, 0, 0) VISIBILITY = 8 class World: def __init__(self): """ Initializes a new World instance - Parameters - - R...
9f43aed5285498aa8e7f474b139e0400fdcb8213
zhu-research-group/RDKitCMD
/nearest_neighbors.py
2,939
3.640625
4
""" Takes a source database (SDFile) and finds the nearest neighbor in a target database (SDFile), based of MACCS keys and the Tanimoto coefficient. Prints out a matrix of Tanimoto coefficients and a file listing nearest neighbors with score. SDFile must contain a name filed and is specified after the database name i...
413e00e0b6e6e3885752ef4f25b02f938c4a7cd3
JSNavas/CursoPython2.7
/Metodos de las Listas/Metodo reverse().py
169
3.75
4
cadena = raw_input('Escribe una palabra para invertir: ') lista = list(cadena) lista.reverse() cadenaInversa = "".join(lista) print 'Cadena al reves:',cadenaInversa
5207a48cab03b6fbcae86412d48252ed98046526
JSNavas/CursoPython2.7
/31. encapsulacion con (property).py
236
3.59375
4
class Fecha(object): def __init__(self): self.__dia = 1 def getDia(self): return self.__dia def setDia(self, dia): self.__dia = 28 dia = property(getDia, setDia) Fecha = Fecha() Fecha.dia = 33 print Fecha.dia
cf8cb8d7598c1e02d3032a78f6e01743616769b7
JSNavas/CursoPython2.7
/15. funciones locales.py
425
3.640625
4
# Para declarar una funcion local se utiliza la palabra reservada"def" # luego el nombre de la funcion, entre parentesis "()" losdatos que se # le van a pasar a la funcion y para cerrar la declaracion ":". # Declaracion de la funcion local pasandole un parametro def saludo(elnombre): print "Bienvenido",elnombre nom...
e13a6a3c3047813a8f6aeff7232b8efb65855cf8
JSNavas/CursoPython2.7
/7.listas.py
1,401
4.75
5
# Listas = arreglos o vectores # Acceder a listas dentro de otra lista # Se accede a traves del indice de donde se encuentra la lista # que esta dentro de la lista principal y al lado se coloca el # indice al que queramos acceder de la lista que esta adentro. # En este caso la lista que esta adentro se encuentra e...
ed39d84817a53a92653ba790fa7f07eab43783db
gdg-garage/garage-trip-2.0
/first-mail-code/encode.py
280
3.609375
4
def main(): text = "See you at Garage Trip 2.0!" ascii_codes = (ord(i) for i in text) shift = -42 shifted = (i + shift for i in ascii_codes) hexed = (hex(i).replace("0x", "") for i in shifted) print(' '.join(hexed)) if __name__ == '__main__': main()
fad4336d374cd8e6ac51c505af41eaceafb62eef
raphaelerbynn/internship-turntabl
/guess_number.py
933
4
4
import random def guess(correct_num): user_guess = int(input('Guess an integer between 1 and 50: ')) if 1 < user_guess < 50: if user_guess > correct_num: print('You going too high') elif user_guess < correct_num: print('You going too low') else: prin...
07ee12f14335eedc844f641077c839bc529abadf
raamshivajigoulikar/PythonFucntions
/Filecheck.py
2,063
3.59375
4
def chkvars(chkData, chkVarNames, chkDataType): """ :param chkData: The name of the dataset that contains the variable to be checked :param chkVarNames: A space delimited list of variables to check for specified dataset :param chkDataType: The expected data type, N for numeric and C for char :return...
1463e3edfcb3e5d1d4aff64ad511333b3b83fae4
hal00alex/DGraphs-
/Dijkstra.py
2,089
3.65625
4
def main(): x = 1 #nodes nodes = ('A', 'B', 'C', 'D', 'E', 'F', 'G') #edges/weights distances = { 'B': {'A': 5, 'D': 1, 'G': 2}, 'A': {'B': 5, 'D': 3, 'E': 12, 'F' :5}, 'D': {'B': 1, 'G': 1, 'E': 1, 'A': 3}, 'G': {'B': 2, 'D': 1, 'C': 2}, 'C': {'G': 2, 'E': 1, 'F': 16}, ...
eca6a66eeda13cb4210b6e98bbc54a1e80c12597
leoh192/my-learning-notes
/Leetcode/21_Merge Two Sorted Lists_06170231.py
523
3.8125
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def mergeTwoLists(self, l1, l2): a = ListNode(-1) b = a while l1 and l2: if l1.val <= l2.val: ...
25c6edeebb52250b63b06b8d9a2f76144e214842
Mangluu/Data-Structures-Algorithms
/Sorting/1. Bubble Sort.py
263
3.96875
4
def bubble_sort(arr): for j in range(len(arr)-1, 1, -1): print(arr) for i in range(0, j): if arr[i] > arr[i+1]: arr[i], arr[i+1] = arr[i+1], arr[i] return l = [6, 8, 1, 4, 10, 7, 8, 9, 3, 2, 5] bubble_sort(l)
d3385eea6078d855f52668035bd46fc206655ac2
mjoscl/cs-i
/Lab 2/bowties.py
3,928
4.03125
4
""" file: bowties.py language:python3 author: mjoscl@rit.edu michael j oconnor description: this program recurcively draws bowties following a specific algorithm while using lengths of 100 and a recurcive depth of 0-3, as specified by the user """ import turtle def get_depth(): """ this function asks the us...
aa020da124284f25e11dfaef0fcde5328948ef8c
mjoscl/cs-i
/Lab 7/vegas.py
7,948
4.21875
4
""" file: vegas.py language:python3 author: mjoscl@rit.edu michael j oconnor description: lab 7 - this card game simulation first prompts the user for the number of cards to play in a deck as well as the number of rounds to play. the game is then simulated followed by a summary of the money spent and earned and relativ...
c7f941008f4aa98f372772d27c96515c4add5b33
mjoscl/cs-i
/Homework 6/lru copy.py
5,415
3.609375
4
""" file: lru.py language:python3 author: mjoscl@rit.edu michael j oconnor description: homework 6 """ from rit_lib import * def put_in_cache(entry,cache): """ this function installs the entry into the first 'empty' location in the cache and returns the index of the new entry in the cache. @precondit...
c8a2e849fdc36d5cc6411fb444b17547bc3317f6
mjoscl/cs-i
/Lab 5/auto_complete.py
7,124
3.859375
4
""" file: auto_complete.py language:python3 author: mjoscl@rit.edu michael j oconnor description: use <> to sort binary search [ ] > [ _|_ ] """ def words_to_list(file): lst=[] for line in open(file): lst += line.split() return lst def is_prefix_match(word,prefix): #print("fin...
aa72bff7c738a70e79fcda73b4dc78ae632d63e4
mjoscl/cs-i
/Lab 5/auto_complete_class.py
1,931
3.9375
4
""" file: auto_complete.py language:python3 author: mjoscl@rit.edu michael j oconnor description: use <> to sort binary search [ ] > [ _|_ ] """ def words_to_list(file): lst=[] for line in open(file): lst += line.split() return lst def is_prefix_match(word,prefix): #print("fi...
b527966ac0abf17a4460c8fa2a4fd08867196ea3
mjoscl/cs-i
/Lab 8/potato.py
4,262
4.28125
4
""" file: potato.py language:python3 author: mjoscl@rit.edu michael j oconnor description:lab8 This program simulates a game of hot potato using pokemon characters pulled from a text file. The program uses a circular doubly-linked list to allow for the passing of the 'hot potato' in either direction, based on a random ...
c6a283c7a69b94272452e8fa0df2296053a621ee
devarias/RetailApp
/retail-api/schemas/order_schema.py
687
3.515625
4
#!/usr/bin/python3 """This module is used to have the class OrderModel to receive the parameters to create a Order in the database.""" from pydantic import BaseModel class OrderModel(BaseModel): """ Class OrderModel to manage the data required from the body to create the Order object to save in the databa...
4b8c74e04ab2d216f31ede1b5d8c57149bda3329
devarias/RetailApp
/retail-api/models/order.py
1,242
3.640625
4
#!/usr/bin/python3 """This module has the class Order.""" import datetime from sqlalchemy import Column, Float, Integer from sqlalchemy import Date, Boolean, String, ForeignKey from sqlalchemy.orm import relationship from .base import Base class Order(Base): """Representation of a Order.""" __tablename__ = '...
1e4d68a9190f4839919fec60798682ece77d9f30
dainonaka/checkio
/most_wanted.py
171
3.5
4
def checkio(text): alphabet = "abcdefghijklmnopqrstuvwxyz" list = [(text.lower()).count(letter) for letter in alphabet] return alphabet[list.index(max(list))]
8b32aa02198d2ec5f6c78f410d46503909e77a31
dainonaka/checkio
/reverse_roman.py
522
3.671875
4
def reverse_roman(roman_string): dict = {"M":1000,"CM":900,"D":500,"CD":400, "C":100, "XC":90, "L":50, "XL":40, "X":10, "IX": 9, "V":5, "IV":4, "I":1} res = 0 while roman_string: if len(roman_string) > 1 and \ roman_string[0:2] in dict.keys(): res += dict[roman_str...
0a61cacc52681d271275445780f0b397f2af90f2
AvisTheAvaxion/Collatz-conjecture
/main.py
267
3.890625
4
from time import sleep ogNum = int(input("Number: ")) num = ogNum while True: if num % 2 == 0: num = num / 2 else: num = ((3*num)+1) num = int(num) print(str(num) + ": " + ("*" * num)) sleep(.1) if num == 1: print("Completed") break
03347c9073840ac9da09d62c75e217d0db49e849
advinstai/python
/solucoes/Duan-Python/Lista1-Python/problem02.py
314
4.375
4
# iteracao manual print("hello, world!") print("hello, world!") print("hello, world!") print("hello, world!") print("--------------") # iteracao com FOR for i in range(1,5): print("hello, world!") print("==============") # iteracao com WHILE j=1 while j<=4: print("hello, world!") j+=1 print("..............")
3789bb48da7c905c0414e30904e3b7af05473316
advinstai/python
/solucoes/Duan-Python/Lista3-Python/p29.py
205
4.1875
4
def enumerate(lista): return [(lista.index(i),i) for i in lista] ''' Testando a funcao lista = ["a","b","c"] print(enumerate(lista)) [print(index,value) for index, value in enumerate(["a","b","c"])] '''
ea2d7ffd01f7acef88807062de8110d0bb8a2c7d
advinstai/python
/solucoes/Duan-Python/Lista1-Python/problem03.py
210
3.671875
4
# O codigo abaixo nao imprime nada na tela. 1 + 2 # Output: Nada # Para imprimir o resultado dessa soma, pode-se fazer: # Opcao 1 print(1+2) print("---") # Output: 3 # Opcao 2 a = 1+2 print(a) # Output: 3
f94832eea13bb9dff1bf8cd2c2ecb46c48446b54
advinstai/python
/solucoes/Duan-Python/Lista2-Python/ex3.py
530
3.765625
4
def raizes2grau(a,b,c): delta = (b**2)-4*a*c if a == 0: print("A equacao inserida nao eh de segundo grau.") else: if delta > 0: print("A equacao possui duas raizes reais distintas.") if delta == 0: print("A equacao possui duas raizes reais iguais.") if delta < 0: print("As raizes da equacao nao sao ...
b70cdd4c3d14e314e6ade7abae6b2acfe0a324da
advinstai/python
/solucoes/Duan-Python/Lista2-Python/ex5.py
166
3.96875
4
import math a = int(input("Insira um numero: ")) if a >= 0: print("Numero positivo. Sua raiz eh",math.sqrt(a)) else: print("Numero negativo. Seu quadrado eh",a*a)
e53e69e956a2d403898abac7b24c4a8d0dd9a726
advinstai/python
/solucoes/Duan-Python/Lista3-Python/p03.py
363
3.859375
4
def somaTudo(lista): if type(lista[0])==int or type(lista[0])==float: resultSoma = sum(lista); else: resultSoma = lista[0] for i in range(1,len(lista)): resultSoma += lista[i] return resultSoma #print(somaTudo([1,2,3])) #pr...
54d6eb02e734a315b6082ab766c44546fc6afd89
advinstai/python
/solucoes/Duan-Python/Lista1-Python/problem10.py
513
4
4
x = 1 def f(): #global x # inicial globalmente x para remover erro y = x x = 2 return x + y #print x #python2 #print f() #python2 #print x #python2 print(x) #python3 print(f()) #python3 print(x) #python3 # Output: ''' 1 Traceback (most recent call last): File "problem10.py", line 11, in <module> ...
a1fe3c0f3668fa25c91295efca16ad0554aa2c8c
advinstai/python
/solucoes/Andre/banco_python.py
1,036
3.609375
4
class Cliente: def __init__(self, nome): self.nome = nome class ClienteFisico(Cliente): def __init__(self, nome, cpf): super().__init__(nome) self.cpf = cpf class ClienteJuridico(Cliente): def __init__(self, nome, cnpj): super().__init__(nome) self.cnpj = cnpj clas...
04f47d88651baa41001f1fdc5e6a8c4d8221241e
advinstai/python
/solucoes/Duan-Python/Lista3-Python/p19.py
466
3.578125
4
import sys # recebendo arquivo como argumento na execucao do programa # e transformando-o em lista lista = list(open(sys.argv[1])) # percorrendo cada elemento da lista (total 4) for line in lista: str = "" # percorrendo cada elemento de cada um dos 4 elementos d lista for i in line: str...
ef3adff304ed5ef11f21fe26b7c110a4d251bfee
advinstai/python
/solucoes/Andre/3-1.py
82
3.65625
4
x = [0, 1, [2]] x[2][0] = 3 print (x) x[2].append(4) print (x) x[2] = 2 print (x)
4353915cf69a92ba5766ac4279c5bef321437926
advinstai/python
/solucoes/Duan-Python/Lista3-Python/p28.py
468
4.03125
4
def triplets(n): if n < 3: return False else: return [(i,j-i,j) for j in range(2,n) for i in range(1,j//2+1)] # print(triplets(15)) # testando a funcao ''' Explicando o codigo: O valor do terceiro elemento, j, eh tomado como base, pois tem-se a referencia de que nao pode ultrapassar o valor maximo do argumento...
2853846a1c6a885775f04aae5df939cb62705e92
advinstai/python
/solucoes/Duan-Python/Lista4-Python/p07.py
480
3.75
4
def prime(limit): if limit <=1: print("Limit must be greater than 1") elif limit == 2: primos = [2] print(primos) return primos elif limit == 3: primos = [2,3] print([2,3]) return primos else: primos = [2,3] lista = list(range(4,limit+1)) for i in lista: for j in range(2,i//2 +1): if i%j=...
1abf6d04623441441ad98d8f787cbc86b187e5c9
advinstai/python
/solucoes/GrupoAleGabiLazaroWana/read_file.py
524
3.625
4
class CSVFile(): def __init__(self): self.arquivo = None self.data = list() # self.data armazena uma lista contendo as linhas do arquivo csv def read_file(self, filePath): try: f = open(filePath,"r", encoding='utf-8') data = f.readlines() self.data = list( map(lambda line: line.strip("\n")....
7d546e29f460c32d31a85f9150b2ad5d3f3ce90a
advinstai/python
/solucoes/Duan-Python/Lista4-Python/p04.py
170
3.828125
4
def showNumbers(limit): lista = list(range(limit+1)) for i in lista: if i%2 == 0: print(i,"EVEN") else: print(i,"ODD") # showNumbers(10) # testando a funcao
2cbff681696df9a7c0e060ad2f294bfbb48a624e
lautomator/renamer
/renamer.py
3,714
3.546875
4
#!/usr/bin/python import os import sys import re def validate_targets(args): ''' Check to ensure all target arguments are files. Returns the valid targets only. ''' valid_targets = [] # At least one argument must be given. if args == []: print 'usage: python renamer.py <a...
91880ba01d1e4a81bab78fa72bf4f47386159728
JanTeffo442/ProgrammingKatas
/hello.py
84
3.53125
4
def hello(): word = str(input()) return word print("Hello " + hello())
5dd01245b2995a30c59d7d05b33a511e343ffdf3
babyehend/GUICalculator
/main.py
3,263
3.5625
4
from tkinter import * root = Tk() root.title("Calculator") root.geometry("360x480") root.resizable(False, False) display = Entry(root) display.grid(row=0, column=0, columnspan=4) def btn_mul_cmd(): display.insert(END, "*") def btn_div_cmd(): display.insert(END, "/") def btn_rem_cmd(): ...
900116e8dbfd73d80f6d0a6f6ea8d956842fb7f5
appfr3d/IT3105-AIProg
/project_1/Pieces.py
1,371
3.8125
4
from enum import Enum import typing class Piece: """ Generic class for all pieces """ def __init__(self, position: tuple): """ :param position: The position of the piece """ self.posistion = position # (row, col) class PegState(Enum): SELECTED = 0 # Last moved UNSELECTED = 1 # Not r...
e1555ceea0220e2827a8d08bc9847274f3639b56
atg-abhijay/Advent-of-Code-2017
/Chal_7/advent_7.py
8,625
3.84375
4
""" URL for challenge: http://adventofcode.com/2017/day/7 """ from tinydb import TinyDB, Query db = TinyDB('db.json') program = {'name': '', 'weight': 0, 'parent': '', 'children': []} def build_db(): f = open("advent_7_input.txt") print("Building db...") # each line denotes one program for line in f....
5c9fa60524b31fbf5bd8b4c193786b2fd356060e
atg-abhijay/Advent-of-Code-2017
/Chal_11/advent_11.py
3,205
3.984375
4
""" URL for challenge: https://adventofcode.com/2017/day/11 """ def main(): f = open("advent_11_input.txt") data = f.readline() commands = data.split(',') """ Consider the 6 directions as 6 vectors - v1 = i + j (ne) v4 = -i -j (sw) v2 = 2j (n) v5 = i - j (se) v3 = -i + j...
d6c33d2dc1ca4b5913aaa65fbc33f4c9622ec43d
EEsparaquia/Python_project
/script2.py
420
4.25
4
#! Python3 # Print functions and String print('This is an example of print function') #Everything in single quots is an String print("\n") print("This is an example of 'Single quots' " ) print("\n") print('We\'re going to store') print("\n") print('Hi'+'There') #Plus sign concatenate both strings print('Hi','There')...
3f66dec3b5f62b6b2accc43ed9b7fded8867928c
EEsparaquia/Python_project
/script14.py
250
4.09375
4
#! Python3 # Programming tutorial: # Writing a File text = 'Simple text to save\nNew Line!' saveFile = open('/Users/ernestosamanom/Computer_Programming/Python/exampleFile.txt','w') print('"w" is for Write') saveFile.write(text) saveFile.close()
5e1d7603eec9b98a94386628eed855ce39e05199
EEsparaquia/Python_project
/script25.py
911
4.40625
4
#! Python3 # Programming tutorial: # Reading from a CSV spreadsheet ## Example of the content of the file ## called example.csv: # 1/2/2014,5,8,red # 1/3/2014,5,2,green # 1/4/2014,9,1,blue import csv with open('example.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') for row in readCSV: print(row...
31be321954539b410d0a1a81dce98c696c9d94df
arslan-gait/leetcode-tree-problems
/06.01_search_in_a_binary_tree.py
1,034
3.9375
4
# https://leetcode.com/problems/search-in-a-binary-search-tree/ class Solution: # recursive # space and time complexity - O(height(root)) def searchBST(self, root: TreeNode, val: int) -> TreeNode: if root is None: return None elif root.val < val: return self.sear...
3b45fe3fc8263dcd4e7d15d1627743655a5c0430
arslan-gait/leetcode-tree-problems
/07.13_530_min_abs_diff_bst.py
709
3.65625
4
# https://leetcode.com/problems/minimum-absolute-difference-in-bst/ class Solution: def __init__(self): self.ans = float('inf') self.prev = -1 # recursive # time complexity - O(nodes(root)) to check every node # space complexity - O(height(root)) def getMinimumDifference(...
4d92ab294dea73d8ee73601676ff67bc2e2c65dd
Adolph97/nlp-reddit-analysis
/pushshift.py
3,612
3.625
4
import pandas as pd import requests import json import datetime import csv """ Name: Amie Kong Description: Python program to gather Reddit Submissions for r/abuse & r/domesticviolence using Pushshift's API and storing them into a CSV format to be further processed for data analysis. Resources: http...