blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
feed2799aaf5178b405a50d033a57382e37de6be
YanHengGo/python
/33_except/lesson.py
883
3.703125
4
#可以捕获所有异常,但不推荐 try: int('abc') sum=1+'1' f=open('abc.txt') print(f.read()) f.close() except : print('出错了T_T') #分别捕获异常 try: sum=1+'1' f=open('abc.txt') print(f.read()) f.close() except OSError as reason: print('文件出错了T_T',reason) except TypeError as reason: print('类型出错了T_T...
045dbac82a08a9490849ef0e36f9e9788014c6de
mobenjamin/replpy
/lexer.py
948
3.875
4
def lex_input(input_string): token = "" output_list = [] i = 0 while i < len(input_string): char = input_string[i] if char == "\"": i += 1 token = char while i < len(input_string) and input_string[i] != "\"": token += input_string[i] ...
f402197274f3908d9209ebd9605551a7c9128a2c
swang99/CS1
/Cities Visualizer/city.py
528
3.796875
4
# name: Stephen Wang # date: November 7, 2020 # purpose: City class class City: def __init__(self, code, name, region, population, latitude, longtitude): self.code = code self.name = name self.region = region self.population = int(population) self.latitude = float...
60c02435ade1624dab567d0d2b837558e78389e2
maps16/ProgramacionF
/Producto2/Python/juego.py
399
3.640625
4
import time print "Hola, es hora de jugar ADIVINA EL NUMERO. Primero piensa en un numero entre 1 y 10" import time time.sleep(5) print "Multiplicalo por 9" import time time.sleep(5) print "Si el numero es de dos digitos, sumalos entre si. Por ejemplo si es 25 -> 2+5=7" import time time.sleep(5) print "El numero res...
ac7b2b9725522f9f52c0d33be5634661b3e281ad
hawahe/leran_frank
/practice/list_comprehension.py
678
3.875
4
a = [x*x for x in range(10)] print(a) a= [x*x for x in range(10) if x % 3 ==0] print(a) a = [(x,y) for x in range(3) for y in range(3)] print(a) result = [] for x in range(3): for y in range(3): result.append((x,y)) print(result) girls = ['alice','bernice','clarice'] boys = ['chris','arnold','bob'] a = ...
96b2bf88d8bafc984c98057ece6eee2584d2b053
cezary4/LearningPython
/projects/fdic/scraper.py
2,904
3.953125
4
#!/usr/bin/env python """ This scrape demonstrates some Python basics using the FDIC's Failed Banks List. It contains a function that downloads a single web page, uses a 3rd-party library to extract data from the HTML, and packages up the data into a reusable list of data "row". NOTE: The original FDIC data is locate...
9f8e199968a12fa56c7dfc47b82f1c79538f01f5
PLivdan/gender
/genderize.py
8,152
3.53125
4
""" Created on Tue Sep 10 14:07:15 2019 @author: tickc """ import csv import os import nltk import random ############################################################################# # # A necessary utility for accessing the data local to the installation. # #########################################################...
cbcd33917e029920d425ec24df9cdddb8418ddd2
rronakk/Python-3-exercies
/treehouse/pick_a_num.py
1,310
4.0625
4
import random def computer_choice(): return random.randint(1, 10) def user_choice(): num = input("Guess a number between 1 to 10: ") return int(num) def game_rules(): print("Welcome to Guess a number game") print("Guess a number between 1 to 10, if your guess matches the number guessed by compu...
9198042369289921a55ec43c065975618941301d
toejellyfutbol/childdir
/ex15a.py
301
3.875
4
# import the argument variables from sys import argv # designates variables to be unpacked script, filename = argv #designates txt as the content of the filename txt = open(filename) #print presentation of file's name print "Here's your file %r:" % filename #print content of file print txt.read()
da88d7bc35b92671a35dfea43cd6cdbffc89e037
devNaresh/DS-Algo
/stringSerching/RabinKarpSearch.py
1,831
3.6875
4
__author__ = '__naresh__' # Implementation of Rabin Karp substring Search """ Time Complexibility O(m*n) https://www.youtube.com/watch?v=H4VrKHVG5qI Application -- Generally used for serching of multiple patterns """ PRIME_NUMBER = 101 def create_hash(pattern): length = len(pattern) ...
0769d3cd2170d8af918a5bc9dc48275d1b413dcd
agarwalsanket/TheBalancePuzzle
/balances.py
10,401
3.875
4
import turtle import os __author__ = "Sanket Agarwal" """ This program is the implementation of the problem stated in HW7. Authors: Sanket Agarwal (sa3250@rit.edu) """ class Beam: """ Beam class contains data about a beam. """ __slots__ = 'beam', 'beam_name_objects', 'beam_draw' def __init__(sel...
c171aecc5ede4d84e5c26cae33ad668873c6f031
Navarroo/Algoritimos
/Aulas/aula25escrita.py
420
3.625
4
# ========MODOS DE LEITURA DE ARQUIVOS========= # r = read ( leitura) # a = write (escrita) # w = delete and create new (escrita em arquivo em branco) # open retorna um endereço para o arquivo arq = open("arquivos/nomes.txt", "w") # escreve alguma coisa no arquivo arq.write("Navarro\n") nome = input("Informe seu n...
330221a75ec044bea63629ba2a28db4c5ee228b6
grassit/leetcode
/46.py
572
3.640625
4
# ref: https://leetcode.com/discuss/18212/my-elegant-recursive # -c-solution-with-inline-explanation # ref: https://discuss.leetcode.com/topic/17277/one-liners-in-python class Solution(object): def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] ...
4ac3fb5a6a42d5cc90316b34b9f78acb0a531a21
TimotheusJX/Algo_code
/twoSum.py
592
3.515625
4
''' example: Given num array [2, 7, 11, 15], target = 9 return [0, 1] assumption: each input has one soln and same element may not use twice ''' class TwoSumSolution(object): def twoSum(self, nums, target): mapping = {} for index, value in enumerate(nums): result = target - value ...
f285b74cd89ca95b08d2fdbe20c166ac13e5fa82
arkellmer/python-4-5-class
/meaningoflife.py
1,465
3.890625
4
from tkinter import * class Application(Frame): """gui application which can reveal the secret of longevity""" def __init__(self, master): """initialize the frame""" super(Application, self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): ...
a9c9a2dbd646460fcc048e71e4e14a47dc49ef4f
seanaleid/Intro-Python-I
/src/11_args.py
2,981
4.46875
4
# Experiment with positional arguments, arbitrary arguments, and keyword # arguments. # Write a function f1 that takes two integer positional arguments and returns # the sum. This is what you'd consider to be a regular, normal function. # YOUR CODE HERE def f1(num1, num2): return num1 + num2 # print(f1(1, 2)) #...
065c6161a7438d6ed9559cea4e18c2bf9ac86480
taddes/AlgoChallenge
/bubble_sort/py/bubble_sort.py
360
3.96875
4
""" Implementation of Bubble Sort """ def bubble_sort(arr): for i in range(len(arr)): for j in range(len(arr) - i - 1): if j < arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] print(arr) return arr test_arr_1 = [14, 78, 2587, 3, 687, 21] test_arr_2 = [85, 14, ...
6c438d4c19fed278778d3ca38603046cc4d749bb
waredeepak/python_basic_beginners_programs
/in.python.basic/ExponentialProgram.py
185
4.15625
4
num=int(input("enter any number you want to : ")) exp=int(input("enter exponential number: ")) result=1 for i in range(1,(exp+1)): result=result*num print("The result is : ",result)
c360cbc38f7f6600915a9fc2413bcbbbedf38f85
EwanThomas0o/Self_teaching
/SEMF.py
668
3.609375
4
def binding_energy_calculator(A,Z): #All in MeV BE1 = 15.56*A - 17.23*(A**(2/3)) - 0.697*(Z**2)*(A**(-1/3)) - 23.285*((A-2*Z)**2)/A if (A-Z)%2 != 0 and Z%2 != 0: #This if statement deals with the pairing term BE2 = BE1 + (12/(A**0.5)) elif A%2 !=0: BE2 = BE1 else: BE2 = BE1 ...
fa98f9b2ec32cec12e8d010a8c94d65583693a17
Masetto97/PROCESADORES_DE_LENGUAJE
/Moore/environment.py
626
3.59375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import Player from player from random import randint class Square(object): def __init__(self, size, n_treasures): self.place = [range(size) for i in range(size)] self.n_treasures = n_treasures self.treasure_position = {} def hide_treasur...
70351c2b399d750a83132744b01592cae2af073c
ashikurcmt126/python-basic
/program27.py
192
3.640625
4
# map function() def square(x): return x*x num = [10,20,30,40] a = list(map(square,num)) print(a) # filter() num = [1,2,3,4,5] result = list(filter(lambda x:x%2==0,num)) print(result)
219ef2757f4e612eb5968345651e371c8ba081df
mnogom/python-project-lvl1
/brain_games/games/calc.py
1,250
4.09375
4
"""Description of the rules for game 'brain-calc'.""" import random # -- Description DESCRIPTION = "What is the result of the expression?" # -- Constants MIN = 0 MAX = 100 OPERATIONS = "+-*" def _calculate_result(number_1: int, number_2: int, operation: str) -> int: """Returns result of calculation a mathemati...
236bf9c996e83985e8dd1a0afc75db16ea180e14
manhar336/manohar_learning_python_kesav
/Datatypes/Strings/Strings_Methods2.py
800
4.15625
4
1. lower() method--lower method returns string in lower case. 2. upper() method-- upper method returns string in upper case. 3. replace() method--replace method replaces with other string 4. Split() method --splits the string into substrings if it finds instances of the separator. 5. rfind() method --- it will search s...
0d6f6338b02f2432b8306ba215697de7e88ec067
neeraj70/Hello-World
/cowbull.py
1,620
3.90625
4
import random WORDLENGTH = 6 WORDFILE = "sixwords.txt" FILELENGTH = 17443 def findcowsandbulls(inputword, guessword): word = inputword.upper() bull, cow = 0, 0 for w in word: # type: object if guessword.find(w) == -1: continue if word.find(w) == guessword.find(w): ...
17a8a9ef9a8dddbf7ec98a212ae92b66f35dab33
leolahara/leolahara
/assignment3.py
6,530
4.28125
4
# assignment3.py # # Student name: Leola Hara # Student id: V00923578 import math # imports Python's math library for your use (ie. math.sqrt) THRESHOLD = 0.1 # to be used to compare floating point values passed = 0 # number of tests passed tests = 0 # number of tests run def main(): ''' Complet...
724199b337b479515c43b433aa72bd2b0a3d27de
akashdeep-chitransh/Python-basic-programms
/Introduction/add.py
191
4.15625
4
# this program wil add two numbers.. print("Enter two numbers below..") a = int(input("Enter first number:")) b = int(input("Enter second number:")) print("Sum of this two numbers is ",a+b)
8c74e32212904d2f95aeddc8b12fdc476f051883
EnriqueZepeda/Python_Skills
/Chapter7/Ex_7_1.py
255
3.859375
4
file = input('Enter a file name:') try: fileHandle = open(file) except: print('Error: file', file, 'no found') quit() count = 0 for lines in fileHandle: lines = lines.rstrip() print(lines.upper()) count = count + 1;
608e9a4dc43ca3a3bf5e3ff585c387166f877b98
Oldby141/learning
/shopping/__init__.py
1,178
3.921875
4
product_list=[ ('Iphone',5000), ('MacPro',9000), ('Bike',500), ('watch',200), ('cofe',20), ] shopping_list=[] salary=input("请输入你的薪水") if salary.isdigit(): salary = int(salary) while True: for index,item in enumerate(product_list): print(index,item) user_choice = i...
b95ea023b8fd04ff5d5849b27181b0fe23400c0f
yuks0810/cloud9-python-course-TA
/Lesson13/def2.py
311
3.609375
4
def introduce(name = "N/A", age = "??"): print("Hello!") print(f"My name is {name}.") print(f"I'm {age} years old.") introduce("tanaka", 25) # 引数を全て指定 introduce("suzuki") # age を省略 introduce(age = 30) # name を省略 introduce() # name も age も省略
afe8e849fcbd9952846ad145abc46cb4552f7578
LearnCodingTogether/PythonAdvanced
/DataFraming_Using_PANDAS/DropingDataFrame.py
400
4.09375
4
import pandas df1=pandas.read_json("supermarkets.json") df1=df1.set_index("Address") print(df1) #Deleting row(0 is for row) having address "3666 21st St" print(df1.drop("3666 21st St",0)) #drop column(1 is for column) named as City print(df1.drop("City",1)) #Drop row from 0 to 2 print(df1.drop(df1.inde...
087305d0e24886384841d6bf0eb421ffe6d75a8e
Xisouyang/CS_1.3
/Lessons/source/sets.py
2,420
4.09375
4
#!python # this implementation of the Set class is backed by hash tables from hashtable import HashTable class Set(object): def __init__(self, elements=None): # initialize a new empty set structure, and add each element if a sequence is given self.hash_set = HashTable() if elements != No...
b9cf5887120a5658bd955995fc5ff2627a827e26
shamurti/Python_Class
/class_test.py
1,228
3.75
4
# Creating a simple dictionary ''' def netw_device(ip, username, password): net_dev = {} net_dev['ip'] = ip net_dev['username'] = username net_dev['password'] = password return net_dev ''' # Now creating the same but using Classes ''' Creating the class object. "object" below refers to base object. If inhertin...
813c48a19ca8e979b66c95fba95fe1a815586570
drekuru/CSUS-CPE-CSC-EEE-Materials
/PHYS 162/Homework/Solutions/HW05-Plotting/HW05-Problem3.py
3,663
3.625
4
#!python 3 # Problem 3-b on Matplotlib-I HW # Because of the "if" statements, the "ground" function does not work for arrays, and a loop is necessary to # apply to xdata before plotting. "numpy.piecewise" make it possible to go around this (see online documentation). import numpy as np import matplotlib.pyplot as pl...
77e79dab65a34a0faac460b86de59ffb9b7686e1
Faiznurullah/HacktoberFest-Python
/codes/AI-Summer-Course/py-master/Basics/Exercise/16_class_and_objects/16_class_and_objects.py
534
4.0625
4
class Employee: def __init__(self, id, name): self.id = id self.name = name def display(self): print(f"ID: {self.id} \nName: {self.name}") # Creating a emp instance of Employee class emp = Employee(1, "coder") emp.display() # Deleting the property of object del emp.id # Deleting the...
3cd6ec2b1c18f26b6f2bfd0a2c85e7a8a67f4f38
mehdiebrahim/Stanford-Algorithms---Coursera
/Divide and Conquer, Sorting and Searching, and Randomized Algorithms/Week 2/noofinversions.py
2,008
3.9375
4
import pandas as pd import sys import os os.chdir('/Users/mehdiebrahim/Desktop/Coding/Stanford Algorithms - Data') data = pd.read_csv('numbers.txt',sep=' ',header=None) data.columns = ['a'] L = list(data['a']) n = len(L) inv_count = 0 def Merge(L,R,mid): global inv_count result = [0]*(len(L)+len(R)) #tem...
3e6a1d132bbcd9e1420b259fdcecd8db15111960
sakshi2829/job-recruitment-and-selection
/str.py
93
3.8125
4
n=6 def square(n) return n*n print "the square of "+str(n)+"is"+str(square(n))
8d70f88650df97853f8b48aef48d8652fe7413f9
himanshusoni30/PythonProjects
/PythonBootCamp/isOrEqualTo.py
633
4.0625
4
a = [1,2] b = [1,2] print(f"type of variable 'a' is: {type(a)}, the value of variable 'a' is: {a}") print() print(f"type of variable 'b' is: {type(b)}, the value of variable 'b' is: {b}") print() if(a == b): print("Condition: a == b") print(f"a: {a} is equal to the value of b: {b}") else: print("Condition: a == b")...
a9dbea13d1a3aa2bcaca321e63573c7d137d6f30
sanstwy777/Leetcode
/MySolutions/836. Rectangle Overlap/836.py
914
3.890625
4
# ============================================================================ # Name : Leetcode.836. Rectangle Overlap # Author : sanstwy27 # Version : Version 1.0.0 # Copyright : # Description : Any % # Reference : # ============================================================================ fro...
1753b9826e8ef787883b566a21bc9a0b6c180c2c
icoding2016/study
/PY/free_exercise/find_intersection_of_2_linked_list.py
2,064
3.859375
4
# Find intersection node of 2 linked lists # Easy class LinkedNode(object): def __init__(self, value=None): self.value = value self.next = None @classmethod def generate(cls, data:list) -> 'LinkedNode': head = None cur = None for d in data: if not ...
80718805bad3d0030c2edf8b64c279cd90038010
paul-pias/Euler-Problem-Practice-
/Smallest Multiple.py
138
3.765625
4
def gcd(x,y): return y and gcd(y,x%y) or x def lcm(x,y): return x*y / gcd(x,y) n=1 for i in range(1,10): n=lcm(n,i) print(n)
10dcda47418a22bb6545b625589d419b1b0ba2a7
jomazu/PythonNotes
/03-Numbers.py
1,359
4.34375
4
# Calculate the area of a rectangle (Area = Width x Length) Width = float(input('What is the width of your rectangle? ')) Length = float(input('What is the length of your rectangle? ')) Area = Width * Length print('The area of your rectangle is %.2f' %Area) print('\n') # Calculate the area of a triangle (Area = Wid...
15dc5f957a6ec22f397b9ea05da5813c32ce2a45
benchen0955/c_call_python
/hello_e.py
373
3.546875
4
# hello.py class HHello_c: def __init__(self, x): self.x=x print("init") # self.x=x # self.x = x # print("====") def printt(self,a=None): print("====") print(a) return str(a) # return def xprint(): print("hello world") # if __name__ == "__main__": # xprint() # ...
d1c79747239540536114ea0289cea3ca9924d7fa
KChen-lab/Cyclum
/cyclum/hdfrw.py
1,710
3.65625
4
"""Read write HDF.""" import h5py import pandas import numpy from typing import Type, Union, List def hdf2mat(filepath: str, dtype: Type = float) -> pandas.DataFrame: """Read hdf generated by hdfrw.R mat2hdf function to a data frame. Note that due to how python and R handles data differently, colnames are for...
578c4bc5f64facf7141a0bb5bffe235e17d49376
cloeffler745/back-up
/code/test/ditance_func/test_alg.py
1,183
3.875
4
import Levenshtein import numpy as np import random import string import sys first = sys.argv[1] second = sys.argv[2] ## Algorithm ------------------------------------------------------------------- def edit_distance(s, t): """Edit distance of strings s and t. O(len(s) * len(t)). Prime example of a dynamic...
231dea1fd60d3a3c29cc8eef1c9d8dbd2ed5bf29
superwenqistyle/1803
/07day/练习/计算器条件.py
400
3.890625
4
x = float(input("请输入数字")) y = float(input("请输入数字")) tar = input("请输入运算符号:+-*/**") if tar == "+": print(x+y) else: if tar == "-": print(x-y) else: if tar == "*": print(x*y) else: if tar == "/": print(x/y) else: if ta...
3af78491444628d97e3b2e8a5481939986befec2
danieljohnson107/EmpDat-Payroll
/Checkpoints/Sprint Something/FindEmployee.py
11,398
3.859375
4
from tkinter import * # from PIL import imageTk, Image from UserData import * from GuiValues import * from tkinter.filedialog import askopenfilename ud = UserData() gv = GuiValues() ''' to use images yoy need to install pillow install with "pip install pillow" on your python to use ImageTk.PhotoImage(Image.open("im...
30672def0094e409e25c488e8ac5b062bd88a48f
rish987/Pokemon-NLP-Research-Project
/code_re/keyword_finder.py
4,487
3.65625
4
# File: keyword_finder.py # Author(s): Rishikesh Vaishnav, Jessica Iacovelli, Bonnie Chen # Created: 13/06/2018 # Description: An interactive program that finds forwards/backwards keywords and # forwards/backwards descriptor label pairs for a certain relation. from constants import *; import re; import pickle; from d...
e9cb8e7afafae54376631a9702bd8102f233498e
wnsgur1198/python_practice
/ex10.py
194
3.515625
4
# 편의점 재고 관리 items = {"커피":7, "펜":3, "종이컵":2, "우유":1, "콜라":4, "책":5} item = input("물건의 이름을 입력하시오: ") print("개수: " + str(items[item]))
e32d0f69f813b1ab43699664e3a657caffd7e1d8
weifanhaha/leetcode
/python3/q151-200/189_Rotate_Array.py
747
3.734375
4
from typing import List class Solution: def rotate(self, nums: List[int], k: int) -> None: def reverse(l, i, j): while i < j: l[i], l[j] = l[j], l[i] i, j = i + 1, j - 1 k = k % len(nums) reverse(nums, 0, len(nums) - 1) reverse(nums, 0, ...
fb74ec16a879cd4c2a5e30d98f95d24084a143ec
Baistan/FirstProject
/training/ОЗ1.py
230
3.890625
4
s = input() upper = 0 lower = 0 for i in s: if i.isupper(): upper += 1 elif i.islower(): lower += 1 if upper > lower: s1 = s.upper() print(s1) elif lower >= upper: s2 = s.lower() print(s2)
088e0395759008cb5003693510dc29a5e002968b
ojcoder/hangman-game
/hangman.py
1,554
3.703125
4
import random print("Welcome to hangman! You will have 10 attempts at guessing the word.\n") print("_", end=" ") print("_", end=" ") print("_", end=" ") print("_", end=" ") print("_") l1="_" l2="_" l3="_" l4="_" l5="_" n1="" n2="" n3="" n4="" n5="" counter = 0 wordlist=["night","fried","shelf","frame"] x=random.cho...
b566c68c442ab063e76fcab84c6add9db818e3d0
scottberke/data-structures
/test/trees/binary_tree_traversal_test.py
2,134
3.640625
4
import unittest from io import StringIO from contextlib import * from data_structures.basic_composites.trees.binary_search_tree import * from data_structures.basic_composites.trees.binary_tree_traversal import * class BinaryTreeTraversalTest(unittest.TestCase): # Helpers def create_tree(self): # Lets c...
f550f4f7410410efa2bbb23bc320be317d6d9b05
llliuer/my-leetcode
/leetcode-python/将有序数组转化为二叉搜索树.py
543
3.6875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def sortedArrayToBST(self, nums: List[int]) -> TreeNode: def dfs(nums): if len(nums) == 0: return Non...
bada2378c98df9e8bd110052029ca73215239233
miyukozuki07/Paola_Avila_1358
/arrays/Array_2D.py
1,314
3.75
4
""" Array 2D(filas,columnas) get_num_rows() ----> regresa una fila get_num_cols() ----> regresa columnas clearing(value) set_item(r,c,valor) get_item(r,c) """ class Array2D: #Los nombres de las clases inician con la primera letra en mayúscula def __init__(self,filas,columnas): #La clase array posee dos...
95d34d68a1216f65bda8d7db662136a2dce20ad4
W3BGUY/CodeEval_w3bguy
/01.Easy/Python/097.20170226_FindAWriter.py
1,191
4.1875
4
#!Python3 ''' FIND A WRITER Description You have a set of rows with names of famous writers encoded inside. Each row is divided into 2 parts by pipe char (|). The first part has a writer's name. The second part is a "key" to generate a name. Your goal is to go through each number in the key (numbers are separated by...
79b54aa7eab62a1c5270c632e3b8e3e642c1451c
pernici/sympy
/sympy/series/residues.py
1,962
3.859375
4
""" This module implements the Residue function and related tools for working with residues. """ from sympy import Wild, sympify, Integer, Add def residue(expr, x, x0): """ Finds the residue of ``expr`` at the point x=x0. The residue is defined as the coefficient of 1/(x-x0) in the power series expan...
447381d6e7f770a14e244bf2b675991036736d8e
monanks/DailyCodingChallange
/Problem#4/solution.py
705
3.59375
4
def solution(arr): """ time complexity: O(N) space complexity: O(1) """ if not arr: return 1 #shifting all negative elements to left j = 0 for i in range(len(arr)): if arr[i] <= 0: arr[i], arr[j] = arr[j], arr[i] j += 1 for i in range...
3a4b4021c621f8bc380d678831a3f9acf30237cf
pulosez/Python-Crash-Course-2e-Basics
/#6: Dictionaries/human.py
720
3.953125
4
# 6.1. human_0 = { 'first_name': 'john', 'last_name': 'connor', 'age': 44, 'city': 'los angeles', } print(human_0) print(human_0['first_name'].title()) print(human_0['last_name'].title()) print(human_0['age']) print(human_0['city'].title()) # 6.7. human_1 = { 'first_name': 'sofi', 'last_name'...
5dc072e89b68b964eafe58210818807af1f69573
inverseundefined/DataCamp
/01-Introduction_to_Python/03-Functions_and_Packages/02-Help!.py
909
3.78125
4
''' Help! Maybe you already know the name of a Python function, but you still have to figure out how to use it. Ironically, you have to ask for information about a function with another function: help(). In IPython specifically, you can also use ? before the function name. To get help on the max() function, for ex...
5354706a818b2accec51f8267740098c80ed6fe5
nikonoff16/learn2code
/Stepik - Begginers Python/football.py
2,924
3.53125
4
#! /usr/bin/python3 #! python3 # -*- coding: utf-8 ''' ЧАСТЬ ПЕРВАЯ - ВВОД ДАННЫХ В ПРОГРАММУ Создаем двумерный массив из данных, удобный для последовательной обработки. ''' matches_quantity = int(input()) list_of_matches = [] for match in range(matches_quantity): list_of_matches += [[foo for foo in input().split...
4eeca2afef712415b09b5d463523fa4360b62a46
sungminoh/algorithms
/leetcode/solved/210_Course_Schedule_II/solution.py
3,618
4.1875
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2020 sungminoh <smoh2044@gmail.com> # # Distributed under terms of the MIT license. """ There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i]...
58e507318867f3708edb82e4d25a479006b72f88
feremore/classes-exercise
/OrangeTree.py
1,092
4.125
4
class OrangeTree: # Trees should start at the age of 0. # Trees should start at a height of 0. def __init__(self): self.age = 0 self.height = 0 # Each growing season. # A tree should age one year. # A tree should grow 2.5 feet taller until it reaches its maximum height, say 25 feet. # A tree sh...
79d971085beeb3009d2db5e9887510056d0fe168
mjancen/sudoku-solver
/sudoku-solver.py
4,985
3.578125
4
#!/usr/bin/env python3 # solver.py - takes a sudoku puzzle, outputs the solution # NOTE: cell rows and columns will be 0-indexed, # while boxes will be 1-indexed import random import time from collections import deque import numpy as np LINE = '|' BOX_LINE = '||' HLINE = '-----------------------------------------\n'...
6873225a8843395a24a756922f81ac87b7fd5135
ejohnso9/programming
/kattis/python/other/anagramcounting.py
1,221
3.609375
4
#!/usr/bin/env python # Python 3 (dev under Python 3.6.1) """ 2019Apr24 https://open.kattis.com/problems/anagramcounting """ import sys, math import operator from functools import reduce import pdb def nAnagrams(s): n = len(s) d = {} for c in list(s): if not c in d.keys(): d[c] = 1 ...
f1428c5651932ae9711a5304c14874616a57e72e
X-H-W/xhw
/所有.py/作业/定义二.py
641
3.984375
4
# 汽车类 class car: def __init__(self,newname): self.name = newname self.price = '50000000' def move(self): print(self.name,'移动') def toot(self): print('鸣叫') # 创建一个实例对象 red_car = car('宝马') red_car.move() red_car.color = 'red' print('内存地址1:',id(red_car),red_car.color) blue_...
d77a0d998f80e2f515a237c524b3a688bfb7def3
ranafge/all-documnent-projects
/scrapy_projt/regex_onely/regex_positive_lookahead.py
141
3.640625
4
import re text ="""SAMAndMAX SAMAndMax SamAndMax SamAndMAX""" res = re.split(r"(?=[A-Z][a-z])|(?=[a-z])(?=[A-Z])|[\n]", text) print(res)
55284b062bfce8486d3955d107f02cac93a0ddf8
Shirleybini/Python-Projects
/Ping-Pong/line.py
372
3.578125
4
# -*- coding: utf-8 -*- """ Created on Mon Dec 28 19:55:26 2020 @author: Shirley Sinha """ from turtle import Turtle class Line(Turtle): def __init__(self,pos): super().__init__() self.shape("square") self.penup() self.shapesize(stretch_len=0.25,stretch_wid=1) s...
be21a8cf15b425fe600cfbe8f3c7439b94de62db
PyStudyGroup/clases
/Unidad 4/Ejercicios/Sem4Eje3_DiegoCaraballo.py
815
4.125
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # @autor: Diego Caraballo # @date: 10/05/13 # @version: python 2.7.4 # Grupo Estudio Python """Escriba un programa que pida el año actual y un año cualquiera y que escriba cuántos años han pasado desde ese año o cuántos años faltan para llegar a ese año.""" def main()...
242312df5d9a1400d3c949e30faf934df4ad64f2
devashish9599/PythonPractice
/searchmatt.py
191
3.53125
4
a=[[2,43,5], [2,5,8]] count=0 for i in range(len(a)): for j in range(len(a)): if(a[i][j]==a[i]): count=count+1 print count
79ff4446a276fcb2261e5cfe6d1c046c0d593fc5
lizkarimi/day-2
/data type latest.py
392
3.796875
4
def data_type(n): if type(n)==int: if n>100: return n,"more than 100" elif n<100: return n,"less than 100" else: return n,"equal to 100" elif type(n) == str: return len(n) elif n==None: return "no value" elif type(n)==bool: return n elif type(n)==list: try: return n[2] except Exception...
363e4e5c2f5707f8dac721ae83163e9b29b22428
KanagasabapathiE2/PythonLearn
/Assignment2/PrintPattern__8.py
478
4.1875
4
""" Write a program which accept one number and display below pattern. Input : 5 Output : 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 """ def printMatrics(no, char="*"): for row in range(no): for col in range(no): if col > row: break print(col+1, end=" ") print() ...
e830dbc35ba94b5ebc298bf0503b952c763d9bed
chenfangstudy/data_analysis
/chapter_8/01-任务程序/code/任务8.2 分析财政收入数据特征的相关性.py
535
3.59375
4
# -*- coding: utf-8 -*- ############################################################################### ####################### 任务实现 ####################### ############################################################################### # 代码 8-1 import numpy as np import pandas as pd in...
692ce9734c25b5ef9c7a669648983ecfeb7cbfc4
Jan-zou/LeetCode
/python/String/28_implement_strstr.py
2,576
4
4
# !/usr/bin/env python # -*- coding: utf-8 -*- ''' Description: Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Tags: Two Pointers, String 返回needle在haystack中第一次出现的位置,如果needle不在haystack中,则返回-1。(子串长度为m) + 暴力匹配 Time: O(n*m) Space: O...
322a8d6a705e1061dca4444921ac45c86e540876
MattheusOliveiraBatista/Python3_Mundo03_CursoEmVideo
/Aulas Python/Aula018_02_Lista.py
705
4.1875
4
"""Nessa aula, vamos aprender o que são LISTAS e como utilizar listas em Python. As listas são variáveis compostas que permitem armazenar vários valores em uma mesma estrutura, acessíveis por chaves individuais. """ galera = list() dado = [] maior = menor = 0 for c in range(0, 3): dado.append(str(input('D...
287309bd5babdfff01a715865afe8da83dbc9314
lnsz/Pathfinder
/grid.py
1,794
3.578125
4
import tile as t class Grid: def __init__(self, window, length, height, start, end): self.length = length self.height = height self.start = (start[0], start[1]) self.end = (end[0], end[1]) self.tiles = [] for y in range(height): self.tiles.append([]) ...
c4cc2dc0c763beca4e008daa4ca7be406232bddb
hyh1750522171/ML
/二叉树/广度优先-层次遍历/广度优先.py
1,424
3.78125
4
class Node: def __init__(self, number): self.number = number self.lchild = None self.rchild = None class Tree: lis = [] def __init__(self): self.root = None def add(self, number): node = Node(number) if self.root == None: self.root = node ...
bf0b9943c5622d0b0a283758ffbba6a669a008fc
maciejmoskala/python
/algorithms/elevator_stops_counting.py
953
3.859375
4
def count_elevator_stops(people_weights, people_floores, M, max_people, max_weight): people_count = 0 weight_count = 0 floores = [] solution = 0 for person_weight, person_floor in zip(people_weights, people_floores): if weight_count+person_weight<=max_weight and people_count<max_peop...
eadd1789cd883dbebb91a03c50907090ba7e5f89
Kevin-De/cardgame
/Card_Game.py
7,198
3.84375
4
__author__ = 'Kevin' # save testing 2 import random import time def get_players(): number_of_players = int(input("how many people are playing?")) players = [] # list of players while len(players) < number_of_players: players.append([]) # adds empty sets for each player in the game return pla...
7ad057b8c76e9e140ef565887a35317cb0b40472
AlexGlau/pythonCourse
/functions/age.py
294
4.3125
4
age = input('Enter your age: ') def define_age(age): age = int(age) if 3 <= age < 7: return 'Kindergarten' elif 7 <= age <= 18: return 'School' elif 18 < age <= 23: return 'College' else: return 'Some job' res = define_age(age) print(res)
922360f81680bbac47bc20af00e96d8b7dae059e
tayloa/CSCI1100_Fall2015
/Homeworks/hw2/hw2_part1.py
877
4.15625
4
import math length = raw_input("Length of rectangular prism (m) ==> " ) print length width = raw_input("Width of rectangular prism (m) ==> ") print width height = raw_input("Height of rectangular prism (m) ==> ") print height def volume_prism(length, width, height): volume = length * width * height return volum...
1e645ba4477146155bd4620363e16ebf006c7bc9
Chrlol/Chrlol
/first2/src/var.py
154
3.84375
4
for i in range(1, 5): print(i) else: print('The for loop is over') def sayHi(): print('Hi, I am a module and my name is', __name__)
08a845047e76fc8d951b18c74642a0356e0a1a64
ai-rafique/MorseCode
/main.py
695
3.828125
4
from data import Morse from art import logo morse = Morse() print(logo) while input('Do you wanna do this ? (y or n) :') == 'y': morse.ops() option = input('Which operation do you wish to perform ? :') if option =='a': morse.print_key() elif option =='b': plaintext = in...
b9c00bae3a891ba8807e150baaa6534c3d35df48
rdbruyn/shell-eco-gps-tracker
/gps_system.py
5,752
3.609375
4
import RPi.GPIO as gpio import time import serial import adafruit_gps import math from pathlib import Path def getDistance(coord1, coord2): """ Uses the Haversine formula to calculate the distance between two coordinates given in the (latitude, longitude) in decimal format """ lat1 = math.radians(coor...
66601718aae2cade2ce9e2b9c376a50e60775e71
David92p/Python-workbook
/repetition/Exercise68.py
1,656
4.15625
4
#Compute a Grade Point Average of A, A+, A-, B, B+, B-, C, C+, C-, D, D+, F media = 0 total = 0 while True: letter = input('Enter the grade letter to calculate your average (press esc to exit) ') letter = letter.lower() if letter != 'esc': if letter == 'a' or letter == 'a+' or letter == 'a-': ...
405f97a440e95014ab53388629b8837fa2d028ea
Ch4uwa/PythonPracEx
/product_sum.py
334
3.953125
4
array = [5, 2, [7, -1], 3, [6, [-13, 8], 4]] def productSum(array, multiplier=1): # Write your code here. total = 0 for ele in array: if type(ele) is list: total += productSum(ele, multiplier + 1) else: total += ele return total * multiplier print(productSum(...
63395c443634c131018b1e0561783ab62b3df042
raghumina/Python_basics
/ElifProblem1.py
351
4.25
4
# Python problem using if else # finding the largest number in three numbers print("Please give three numbers") a = 1 b = 5 c = 3 if a>b: print("a is greater than b") if a>c: print("a is greate than c ") print("a is the largest number ") elif b>c: print(" b is the largest number ") else: print("c...
bb1765519d32289d79a8750b80d0ec822cbe2130
Adasumizox/ProgrammingChallenges
/codewars/Python/8 kyu/TipCalculator/calculate_tip_test.py
1,333
3.625
4
from calculate_tip import calculate_tip import unittest class TestTipCalculator(unittest.TestCase): def test(self): self.assertEqual(calculate_tip(30, "poor"), 2) self.assertEqual(calculate_tip(20, "Excellent"), 4) self.assertEqual(calculate_tip(20, "hi"), 'Rating not recognised') ...
53a42169b80a6f53b32d9d1c04fbe3ebce9bd6f5
Vineet2000-dotcom/Competitive-Programming
/CODEFORCES/Young Physicist.py
226
3.65625
4
x1 = y1 = z1 = 0 for _ in range(int(input())): x, y, z = map(int, input().split()) x1 += x y1 += y z1 += z if(x1 == 0 and y1 == 0 and z1 == 0): print("YES") else: print("NO")
aae2d77baf959d378b4ce895c770b8c1be0b174b
thelmuth/cs-101-spring-2021
/Class16/functions.py
663
4.25
4
import matplotlib.pyplot as plt import math ### Gets integers from the user until they enter a blank line ### Store these integers in a list, so we can graph them. # # integers = [] # x = input("Enter an integer: ") # # while x != "": # integers.append(int(x)) # x = input("Enter an integer: ") # # print(int...
9fb31245fd7be7ff5f848361ecb9c457f51545e4
pshoxxx/2002capstone
/menu.py
2,763
3.71875
4
#!/usr/bin/env python3 import webbrowser # Function for port scanner menu def scanner_menu(): # Print out options for client to choose (How many hosts they want to scan? One or multiple) print("How many hosts will you be scanning?") print("1. Single") print("2. Custom") print("3. Return to previous...
b22e6d7c1c1ac1bce59594731d0d1cc3598b6a18
Prad06/Python-DSA
/Arrays and Strings/Arr05.py
452
3.921875
4
# Pradnyesh Choudhari # Sat May 29 19:16:07 2021 # Distribute Candies # Time Complexity O(n) Space Complexity O(n). from itertools import combinations candyType = list(map(int, input().split())) n = len(candyType) possibleTypes = set(candyType) print(min(n//2, len(possibleTypes))) ## Additional question. Print all ...
5227b7cc6cc853529d6bf5899c4ee51197bbcb3a
prkapadnis/Python
/Tuple.py
287
4.25
4
mytuple = tuple() mytuple = (5,4,3,2,1) print(mytuple.__sizeof__()) print(mytuple) print(type(mytuple)) print("The length of Tuple: ", mytuple.__len__()) print(mytuple.__sizeof__()) print(tuple(sorted(mytuple))) # It returns a list after sorting and it creates a new tuple print(mytuple)
a068dbeecbd5c8da0ab040c3455690d73dbf8426
dikyindrah/Python-Basic-02
/100-Latihan Membuat Program Permainan Batu Gunting Kertas Dengan Pemrograman Modular/Permainan.py
825
3.5625
4
import Komputer import Periksa import Status pilihan = ['batu', 'gunting', 'kertas',] print('====={}=====\n'.format('Permainan Batu Gunting Kertas')) user = str(input('Pilih salah satu (batu, gunting, kertas) : ')) pilihan_user = str.lower(user) pilihan_komputer = Komputer.komputer(pilihan) pilihan_user_ada = Peri...
4929f9eb2d244e334c5e2bd4952a1c26e9beba6c
ejimenezdelgado/ext_logico_algoritmo_1_2019
/Semana 9/ejercicio4.py
500
3.65625
4
#Creado por:Efrén Jiménez #Fecha:28/03/2019 #Objetivo: Ejercicio 3 def NumerCercano(): contador=1 menor=0 lista=[] for variable in range(0,5): lista.append(int(input("Digite un numero"))) diferencia=-1 while contador<4: resultado=lista[contador]-lista[0] if resultado<d...
ae9507b3e8aa1739d25a286229508f7014137a45
Lance0404/my_leetcode_study_group
/python/easy/implement_strStr.py
706
3.515625
4
""" https://leetcode.com/problems/implement-strstr/ Runtime: 24 ms, faster than 95.46% of Python3 online submissions for Implement strStr(). Memory Usage: 14.1 MB, less than 8.00% of Python3 online submissions for Implement strStr(). """ class Solution: def strStr(self, haystack: str, needle: str) -> int: ...
918b9fce261694c3a5bb1c806aba3b434c17f38d
RoshaniPatel10994/ITCS1140---Python-
/Modular program/Practice/dog day afternoon 2.py
840
3.8125
4
DogDay class(): Class DogDay: #initialize DogDay object def __init__(self, quantity, size): self.quantity = quantity self.size = size #Determine price of each bone based on size def DeterminePrice(self): if (self.size == 'A'): self.price = 2.29 elif (self.si...
254ebe4e986396ae8a8cd79bc66d5f5f14d78017
axpak7/NumericalMerhods
/task1/mnps.py
2,046
4.25
4
""" Метод наискорейшего покоординатного спуска """ import numpy as np def polynomValue(X): """ Нахождение значения полинома :param X: задание неизвестных переменных x, y, z :return: значение полинома """ x = X[0] y = X[1] z = X[2] return 2 * x ** 2 + 3.1 * y ** 2 + 4.1 * z ** ...
0e21853bea08b986eb4033499712c9dea92efd8d
artthedeath/Estudo-em-Python
/Probability_Calculator.py
1,585
3.546875
4
# -*- coding: utf-8 -*- """ Created on Fri Sep 11 16:15:56 2020 @author: Arthur DOnizeti Rodrigues Dias """ from copy import deepcopy import random class Hat: def __init__(self, **balls): self.balls = balls self.lista_cor =[] self.lista_remove=[] self.contents = self...
ac74c05eee800987dcb3096e3a060d7389b3b986
jaredkhan/tighten-tricky-types
/2-overloading/before.py
1,201
4.34375
4
""" Goal: Define a Circle class which does nothing but storing a radius. It should be initialisable with either a radius or a circumference. """ import math from typing import Optional class Circle: radius: float # Note the use of 'keyword-only' arguments (arguments after *) # This means users must use ...
5c1bb9572e468a56a46f11c61c54a651b39ffbda
bryand1/snippets
/python/algorithms/search/binarysearch.py
391
3.859375
4
def binary_search(A, x): # Initialize search region to the entire array # [lo, hi) lo, hi = 0, len(A) while hi - lo > 1: mid = (hi + lo) // 2 if x < A[mid]: hi = mid elif x == A[mid]: return True else: # x > A[mid] lo = mid + 1 ...