blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
3d3a5b66c5cd1166ab13c31156cff5d02d3e1b86
ashushekar/python-advance-samples
/vendor-machine.py
2,316
4.09375
4
""" Vendor machine problem """ # This will be the money used to purchase the snacks money = 10.00 vending_machine = {"Chips": "0A", "Soda": "0B", "Chocolate": "0C", "Fruit Snacks": "0D"} prices = {"Chips": "$0.75", "Soda": "$0.50", "Chocolate": "$1.25", "Fruit Snacks": "$.25"} # Debug functions def set_money(amount)...
862eae8400bd3bec1dc24749c03fdb93925c9954
gitaukevin/Andelab_FizzBuzz
/Max_Min.py
531
4.09375
4
#this defines the function find_max_min def find_max_min(sample_data): Min_Number= min (sample_data) #first variable with max values of the parameter sample data Max_Number= max (sample_data)#secon variable with min values of the parameter sample_data lists=[] #lists an empty list we'll use to store our output ...
c73702d1b88d8e895ea1044c20955ab0186dae8d
yagomenin/Trabalho-Facul
/4.py
640
3.703125
4
r_1 = input("Telefonou para a vitima ? (s/n)? ") r_2 = input("Esteve no local do crime (s/n)? ") r_3 = input("Mora perto da vitima? (s/n)? ") r_4 = input("Devia para a vitima (s/n)? ") r_5 = input("Ja trabalhou com a vitima (s/n)? ") r = 0 if r_1 == 's': r = r + 1 if r_2 == 's': r = r + 1 if r_3 =...
a1b0f957be984180c34aeea81a9f122d6e4636cb
EvgenChopenko/HomeWork
/task_04_01.py
2,989
3.765625
4
import os# необходима для проверки наличия файла n=int(input()) p=int(input()) #------------------------------------------------------------------------ def str_type(st):# доп функция для удаления избыточных символов DICT = { ord('.'): '', ord(','): '', ord('!'): '', ...
8726b62d012ea1384b4783b96100d2172de4307a
alialavia/python-workshop-1
/second.py
1,217
4.34375
4
""" To evaluate the good or bad score of a tweet, we count the number of good and bad words in it. if a word is good, increase the value of good_words by one else if a word is bad, increase the value of bad_words by one if good_words > bad_words then it's a good tweet otherwise it's a bad tweet """ tweet_string = "T...
f234359becd795ab9f016c823c9f4e7c526b55e5
titanlambda/Lame-Password-Generator
/lamePasswordGenerator.py
930
3.953125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # importing "random" for random operations import random numberOfPasswordToBeGenerated = 50 words = ["wordA", "wordB", "wordC", "wordD", "wordE", "wordF", "wordG", "wordH", "wordI", "wordJ"] special_characters = ['#', '$', '@', '*', '%'] startingNumber = 100 endingNumb...
a149e37489e4572f315a2fc8f80908123c92ff78
NathanGutierrez98/Battleship-game-python
/Practica/Partida.py
1,870
3.671875
4
from Tablero import Tablero from Jugador import Jugador from Maquina import Maquina ''' Created on 28 ene. 2019 @author: Nathan ''' class Partida: while True: try: entrada = int (input("Pulsa 1 para crear una partida\n")) if(entrada == 1): tablero = Tablero() ...
1a27e7c78357d8bc412b087bc98e971f498eb554
caheredia/target_modeling
/src/features/build_features.py
6,340
3.859375
4
from pandas.core.common import array_equivalent import pandas as pd import numpy as np def find_duplicates(df): """Finds the names of duplicate columns. Finds the different data types in a dataframe. Creates a dictionary file with different data types as keys and the pertinent columns as keys. Para...
d8bd11ef9ad0b776b32b9ef51ac9d413b798f6f5
yahirb/coding_challenges
/coding_challenges/clover_health/solution.py
2,000
3.515625
4
class FileConverter(): def get_format(self, filename): try: _instructions = [] # parse formatting file format_file = open(filename, "r") next(format_file) for line in format_file: line = line.strip('\n') line = line....
82b52ca824bd0344f3a82a1926acdf5d53b9018f
wolf877/Notes
/Start/notas.py
1,928
3.59375
4
import time as tm import numpy as np import os while True: try: NL=int(input('Numero de avaliações: ')) break except ValueError: print('Use um numero inteiro') continue while True: try: AL=int(input('Numero de Alunos: ')) break except ValueError: ...
4959c0d549204493719c10fb0b1dbc82917a8837
judening/leetcode
/Tree/pathSum.py
785
3.640625
4
class Solution: def hasPathSum(self,root,sum): self.sums = [] acsum = 0 self.traverse(root,acsum) if sum in sums: return True else: return False def traverse(self,node,acsum): if not node: return elif node.left and node...
8858c28f5e9268759677c62e95a7ce057b0b925b
tanmay2004/Math-Programs
/The Temperature Converter.py
2,633
4.28125
4
# Celsius to Fahrenheit and vice versa import operator def c_to_f(the_temp): the_temp *= 9/5 the_temp += 32 return the_temp def f_to_c(the_temp): the_temp -= 32 the_temp *= 5/9 return the_temp def k_to_c_back(temp, the_op): ans = the_op(temp, 273.15) return ans def k_to_f(temp):...
559d90bb98bd0ca8a82d4337cbd26f0cfbd69477
jhall6226/MITx-6.00
/Lecture 3/secret_number_bisection.py
1,030
4.40625
4
# MITx 6.00 # Lecture 3 - Discussion Question # Jordan Hall # Create a program that will guess a user-defined integer between 0 and 100 using bisection search. # Tell the user to think of a number between 0 and 100. print 'Please think of a number between 0 and 100!' # Set the initial upper and lower bounds upper_bo...
af98ce36071cd28b653bfb399c1c726d2826bb2c
mirmozavr/phonebook
/phonebook_app.py
4,843
3.84375
4
import sqlite3 import time print("PHONEBOOK_APP") # making a connection to existing db or creating new db connection = sqlite3.connect('Phonebook.db') # creating a cursor class obj crsr = connection.cursor() # try to execute table creation (PRIMARY KEY may be used) try: cmd = """CREATE TABLE phonebook (fna...
71af71e8ddcd7987275265a9e6638a377cdefb71
ZuoCaiSong/Python
/Base/func.py
1,880
3.90625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- #函数中的可变参数 #定义可变参数,在参数前面加一个* ,此时可以传入list 或者tupe def cale (*number): sum = 0 for n in number: sum += n*n return sum print cale(1,2) #传入的是一个元祖,省略了() # 2. 如果已经有一个list 或者tupe 需要作为参数传进去,则按照如下调用,且是非常常见 ,当然也可以还原为tupe形式 list1 = [1,2,3] print cale(*list1) # 3. 关键字参数: 自动组装0个或任意...
e5b38acf8e3c5b7e31993a050aaf094866c21db6
JimMcKenzieSmith/Covid-Invasion
/virus.py
673
3.53125
4
import pygame from pygame.sprite import Sprite class Virus(Sprite): """a class to represent a single virus in the fleet""" def __init__(self, ai_game): """initialize the virus and set its starting position""" super().__init__() self.screen = ai_game.screen # load the virus image and set its rect attribute ...
25f6d5ce4ed41b4c5a7e7754edcf25db20345e12
xionghhcs/leetcode
/problem_python/p720.py
504
3.625
4
class Solution: def longestWord(self, words): """ :type words: List[str] :rtype: str """ if not words: return '' words.sort() st = set() res = '' for w in words: if len(w) == 1: st.add(w) ...
55b9ed44e654af70700e25e078004ff52fa3d363
Chetan202/Python_tutorials
/exp3_2.py
144
3.96875
4
l=int(input("Enter the length of square")) area=l**2 perimeter=4*l print("Area of square is: {} and peerimeter is {}".format(area,perimeter) )
8cd1bb5369a83a8feafbe4555ba3b2907d56dbb5
scheidguy/ProjectE
/1-50/prob14.py
476
3.765625
4
# -*- coding: utf-8 -*- """ Created on Thu Sep 17 09:42:48 2020 @author: schei """ longest = 0 longest_num = 0 for num in range(1, 1000001): seq = num length = 1 while seq != 1: if seq % 2 == 0: seq /= 2 else: seq = 3*seq + 1 length += 1 if length > long...
705793ade689a60d33d221f04f2e335dcf7a18d2
ashok052/code_snippets
/Python/DailyInterviewPro/6_SortingList.py
360
3.953125
4
""" Hi, here's your problem today. This problem was recently asked by Google: Given a list of numbers with only 3 unique numbers (1, 2, 3), sort the list in O(n) time. Example 1: Input: [3, 3, 2, 1, 3, 2, 1] Output: [1, 1, 2, 2, 3, 3, 3] """ def sortNums(nums): # Fill this in. pass print(sortNums([3, 3, 2...
a4e2f9212eee35f2e1314295ef5aef8f52b63b9b
swarooppannem/swaroop-pannem
/alphabetornot.py
150
4.09375
4
a=raw_input('Enter the character:') if a.isalpha()==True: print 'The character is a alphabet.' else: print 'The character is not a alphabet.'
aa9232aa0ac7f1d05da1aaec821864db0600c2cf
chapman-cpsc-230/hw4-massimolesti
/histogram1.py
207
3.859375
4
print "Histogram" x = [4, 9, 13, 5] def histogram (): for n in x: for y in range(n): st = "" for col in range (n): st += "*" print st histogram()
f1771f2789f59ce0a01d854073143fd48e557fd8
MasterTuto/Switch-Cipher
/Switch-Cipher.py
2,934
3.765625
4
# -*- coding: utf-8 -*- import string import argparse from os import system, name system('cls') if name == 'nt' else system('clear') print """\033[32m _ _ _ _ _ _ _ _ _ _ _ _ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ ( S | w | i | t | c | h ) ( C | i | p | h | e | r ...
7bc31307fc4b71f84ebdcc2e27de9966936a306b
mahafatima14/Guessing_game
/game.py
1,082
4.0625
4
def guessing_game(): """A number-guessing game.""" print("Hello, Welcome to the guessing game") import random print("Hi") print("Hello, Welcome to the Guessing Game!") name = input("What is your name? ") print("Hey,", name) right_ans = random.randint(1,100) tries = 0 while...
9beb3c5d8b1a78919c604807e41a69f8480ee420
Narzon/PythonProjects
/GuessingGame.py
2,769
4.03125
4
# File: GuessingGame.py # Description: Guess a number a user thinks of between 1 and 100 inclusive using binary search # Student Name: Nicolai Antonov # Student UT EID: naa766 # Course Name: CS 303E # Unique Number: 50860 # Date Created: April 13, 2016 # Date Last Modified: April 13, 2016 def main(): ...
891e096a568733c8829e085b77daec84f950811c
chxtan/Py-script-for-add-stream-of-numbers
/PyScript.py
295
3.984375
4
sum = 0 while True: UserInput = input("Enter the item price or press q to quit: \n") if UserInput != 'q': sum = sum + int(UserInput) print(f"Your total so far.. {sum}") else: print(f"Thank your bill is: {sum}. Thank you for shopping with us") break
77e41a46f31b64926a5527f3abed178ed89f71cf
Ashu827/Devops-Training
/works/second.py
153
4.09375
4
name='' print ('entername') yourname = str(input()) while(name!= yourname): print('please enter name') name = str(input()) print('thanku')
49ab12ea83685d222175196159e1ee04af2c46d9
GeorgeGalaxy/IT_PY_2021_05
/IT 15/IT 15.1.3.py
295
3.890625
4
from math import * a = float(input('input a: ')) b = float(input('input b: ')) h = float(input('input h: ')) x = a value = 0 func = "value = cos(e*x)**3 + sin(fabs(x))" func1 = compile(func, "compiledfunc", 'exec') while x <= b: exec(func1) print(f'x = {x}, value = {value}') x += h
eaa788a75180bec508f54d16275249fedc5620aa
ricardo1470/holbertonschool-higher_level_programming
/0x05-python-exceptions/3-safe_print_division.py
177
3.546875
4
#!/usr/bin/python3 def safe_print_division(a, b): try: i = a / b except: i = None finally: print("Inside result: {}".format(i)) return i
00d0b08247c9ebd5f8b3ee01bd553eabd1881b77
gewoondim1/Principal-Component-Analysis
/PCA.py
5,476
3.578125
4
from pandas import read_csv import numpy as np import matplotlib.pyplot as plt class PCA: def __init__(self, dataframe, columns=None, startvar=0, endvar=0): """ If columns is not None it will be used to classify the data, otherwise the startvar will be used dataframe: the data as a pandas ...
a4b76e402868c09d36bf35210b3b60fbf16ab20d
ahkabir/Deep-learning-using-MSI-Trident3-Nvidia-RTX-2060
/face_rec_tf/face.py
3,853
3.71875
4
"""FACE Parent class definition for face recognition. This describes: - common methods to be used both in training and classification. - user provided configuration data that is used by training and classification. Prgoram that need to perform face recognition should import this file. The training and classificat...
3816b0dcbc098453f003c63c1eae081c7dc3c21e
hsalam/python_learning_1
/16_medicines.py
469
3.828125
4
#!/usr/bin/python n = input("Enter number of medicines : ") medicine_names = [] prices = [] for i in range(n): medicine = raw_input("Enter medicine name %d : " %(i+1)) medicine_names.insert(i,medicine) price = input("Enter price :") prices.insert(i,price) search_medicine = raw_input("Enter medicine name to be sear...
a7989292af4d7c9463d0e575f84f5572a375c6d8
rishi772001/Competetive-programming
/Algorithms/prefix sum/max subarray with eq 0 & 1.py
614
3.65625
4
''' @Author: rishi https://www.geeksforgeeks.org/longest-span-sum-two-binary-arrays/ ''' import sys """ If differences between prefix sums of two arrays become same at two points, then subarrays between these two points have same sum. """ arr1 = [0, 1, 0, 0, 0, 0] arr2 = [1, 0, 1, 0, 0, 1] # ans = 6 def prefix_s...
522526f706b7cd457d0b4c794b8af9d519373fd8
pwang867/LeetCode-Solutions-Python
/0008. String to Integer (atoi).py
2,559
3.9375
4
# sign, and integer overflow """ 1. only those are allowed: " " in the beginning, "+-" in front of numbers, numbers 2. consider integer overflow 3. return 0 if no conversion happens """ class Solution(object): def myAtoi(self, str): """ :type str: str :rtype: int """ # de...
673587e8d84e0f27c020512a8e4f9dd5fa18cb0e
willstem/Project-Euler
/P035.py
1,301
3.71875
4
# -*- coding: utf-8 -*- """ Created on Fri Apr 27 09:50:12 2018 @author: willstem """ from math import sqrt from itertools import combinations_with_replacement, permutations def is_prime(n): if n % 2 == 0 and n > 2 or n <= 1: return False for i in xrange(3, int(sqrt(n)) + 1, 2): if n % i == 0...
f6f7b4db7f31d10e33f9208c6c1a73ecf6402c39
alexpfernandes/adventofcode2020
/advent-day-01.py
607
4.09375
4
# the report_test function takes a list of integers (report) and adds together combinations in sets of (number) to find a set that adds to the (goal) value # it returns the sum of the product of the set of integers that sum to the goal value def report_test(report, number, goal): from itertools import combinat...
caac29b6ec2895297760237efbd256e5c379d45a
jz393/Space-Invaders
/invaders/wave.py
23,502
4.21875
4
""" Subcontroller module for Alien Invaders This module contains the subcontroller to manage a single level or wave in the Alien Invaders game. Instances of Wave represent a single wave. Whenever you move to a new level, you are expected to make a new instance of the class. The subcontroller Wave manages the ship, ...
2e89ab55e922b94da34f9ef1f51c63c133bfd2dc
qubit-finance/algostudy
/w3/M105.py
1,328
3.9375
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 class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: def construct_tree(node, ...
f3af5d28456c3b0fd09e894e24329b4b09e87b90
Aaqib925/Python-Practice
/Error handling.py
1,428
4.09375
4
# there are 4 keywords use for the error handling in the code # try, except, else and finally # if the code in the try block fails then it goes to the expect block....and then to finally... # if the code in try block works then the except block will not be executed # the code in the block of finally is always executed ...
177e92ab8b3d172f2c6b344e88dc954e00c20b7c
valentinemaris/ProjetGroupe5
/checkIndentation.py
2,726
3.671875
4
def retirerIndentation(lines): """ Retire les espaces devant les lignes :param lines: Liste des lignes du fichier """ for i in range(len(lines)): nbSpaces=0 line=lines[i] for char in line: if char==" ": nbSpaces+=1 else: break; lines[i]=lines[i][nbSpaces:] return lines def printInd...
fd77e29303261418671d7b2fdf0108c97d1e20ef
dzhang344/Python_exercise
/answer4.py
214
3.90625
4
# 题目004:输入某年某月某日,判断这一天是这一年的第几天? import time dateStr = input('please enter a date mm/dd/yy ') st = time.strptime(dateStr, '%m/%d/%y') num = st.tm_yday print(num)
bdfe4fbd22a8e27e5b515c44f9bcb86cff91c1f0
shaffer-wv/udacity101
/Sudoku.py
1,165
4.15625
4
#Check to see if square (in the form of a list) is a valide sudoku square #for example [[1,3,2], # [3,2,1], # [2,1,3]] def check_sudoku(x): if check_rows(x) and check_columns(x): return True return False # create a correct sudoku row/column to check against def check_list(length): ...
e2621eebc82a28eda041919974d8aa966d2b52d2
broadlxx/171-172-271python-
/dayi/Assgin 2B-XueXiang-Lv-175150-19023249/Question 1_Xuexiang_Lv_19023249_175150.py
1,898
3.890625
4
print("Name:XueXiang Lv Student ID:175150 Massey ID:19023249") #Name:XueXiang Lv Student ID:175150 Massey ID:19023249 moviefile=open("movietitles.txt","r") line=moviefile.readlines() def Notempty(): #This function is calculating lines a=0 for i in line: if i!=None: a+=1 ret...
f0a722728b930784c9fb551bd89d77d37a2bacee
mishrakeshav/Competitive-Programming
/Code Forces/Round 636/balanced_array.py
741
3.578125
4
from sys import stdin input = stdin.readline for t in range(int(input())): n = int(input()) if (n//2)%2: print('NO') else: i = 2 j = n//2 arr1 = [] arr2 = [] odd = 1 even = 2 while j: if even - odd < 0: arr1.append(e...
eee14836b0a21a3cb3cf1b761f2f832a58228b3f
parrul04/Employee-Registration-Form
/utilites/custom_log.py
728
3.53125
4
import logging import inspect def CustomLogger(loglevel=logging.DEBUG): # It will return the name of the method which call this method loggerName = inspect.stack()[1][3] # create a logger and set level logger = logging.getLogger(loggerName) logger.setLevel(logging.DEBUG) # creating a handle...
1bd0a204d7be7c913cf010226681d5a7265d90c4
akanksha0202/pythonexercise
/course.py
124
3.5
4
course = 'Python Course for "Beginners"' course1 = "Python's Course for Beginners" print(course[-2]) print(course1[1:-1])
d014b68c6bae72b2251594c82da84f8e6b87fa2e
teodoramilcheva/softuni-software-engineering
/Python/Programming Basics/Simple Calculations/10. Radians to Degrees.py
82
3.5
4
import math rad = float(input()) deg = rad * 180 / math.pi print(round(deg, 0))
82027416a20ce43a467f590ff5c73f91a0c10deb
birajparikh16/fsdse-python-assignment-7
/prime_numbers.py
378
3.71875
4
def get_prime_numbers(n): prime=[] if n > 1: for i in range(2,n): for j in range(2,i): if (i%j==0): break else: prime.append(i) else: if n<=1: print "Number is less than one" return prime # get_...
b000935b65c92676b37fe098bc455a57d0d82372
Agrotir/Python-Practice
/Nth Fibonacci Number/Nth_Fibonacci_Number.py
627
4.15625
4
# The Fibonacci sequence is the integer sequence defined by the recurrence relation: # F(n) = F(n-1) + F(n-2), where F(0) = 0 and F(1) = 1. In other words, the nth Fibonacci # number is the sum of the prior two Fibonacci numbers. Below are the first few values of # the sequence: # 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 8...
e3a093f0a5c7e1f57630b9aa9ee580cd2c8d5816
gavin-lihao/meya
/列表.py
3,116
3.703125
4
# fa='fishec' # for i in fa: # print(i,end='') # number=['11','222','33'] # for each in number: # # print(each,len(each)) # # print(range(3)) # # print(list (range(3,10,2))) # # for i in range(10): # # if i%2!=0: # # continue # # print(i) # # print(i) # #列表list # mix=['xiao',1,[1,2,3]]#可...
7f4505049321fc77eb825cd05c020107f1420937
bhanubais/Fundamental-of-Computing
/Course 1. An Introduction to Interactive Programming in Python (Part 1)/01-Practice Exercises for Expressions (optional)/10-expr_point_distance_template.py
699
4.40625
4
'''The distance between two points `(x_0, y_0)` and `(x_1, y_1)` is `sqrt((x_0-x_1)^2 + (y_0-y_1)^2)`. Write a Python statement that calculates and prints the distance between the points (2,2) and (5,6) ''' # Compute the distance between the points (x0, y0) and (x1, y1). ###############################################...
afc52b3dc4d31f2c37d5021b550e74e6a24a4ad3
locorohan42/Python-2061-Exercises
/Chapter 6/RohanAbraham_assign6_12_AverageStepsTaken.py
2,777
4.09375
4
#Rohan Abraham #Reads a file and calculates the average number of steps taken for each month def main(): line = '' number = 0.0 count = 0.0 infile = open('steps.txt', 'r') line = infile.readline() total = 0.0 for count in range(0,31): number = float(line) total+=nu...
b373073b9494afca796972ecc075f3fabcebb116
Lancaster-Physics-Phys389-2020/phys389-2020-project-J-Bow
/Particle.py
1,050
3.578125
4
import numpy as np import math import copy import scipy.constants class Particle: """ Class to model a particle being acted on by a force. Calculates conserved properties. mass in kg position and velocity in m """ def __init__(self, Position=np.array([0,0,0], dtype=float), Veloci...
c4c875ee32d6e5aaaec81beca22969d6b6d5750e
frclasso/revisao_Python_modulo1
/cap17-tratamento-de-excecoes/extras/02_assert.py
700
3.578125
4
#!/usr/bin/env python3 import sys def linux_interaction(): assert ('linux ' in sys.platform), 'Function can only run on Linux systems. ' print("Doing something.") try: linux_interaction() except AssertionError as error: print(error) print("The linux_interaction() function was not executed.") e...
2d2b349aff5c0312d9cb9b7a02bd014fc08d832e
irandijunior1903/SI---Monitoria
/Listas/listas10.py
292
3.78125
4
VetA = [] VetB = [] VetC = [] for x in range(10): VetA.append(int(input("Digite um número inteiro: "))) for y in range(10): VetB.append(int(input("Digite um número inteiro: "))) for z in range(len(VetA)): VetC.append(VetA[z]) VetC.append(VetB[z]) print(VetC) print("FIM")
bdd453eaf6f92c7f2ce63bdefe6c11e55be3d3cd
FreezingKas/Algorithm-and-Vulnerabilty-Chaining
/Vulnerability.py
6,362
3.515625
4
from utils import args_formatter, roundup from variables import parameters_value class Vulnerability: def __init__(self, tab: list): """ Parameters are private because user doesn't have to change parameters TODO: we can change this but i have to build new method to check the validity of ne...
237addd020e62527233f4f6df0c2f4d29327a0d3
Qiao-Liang/LeetCode
/LC680.py
942
3.53125
4
class Solution: def validPalindrome(self, s: str) -> bool: def recurse(l, r, d): while l < r: if s[l] == s[r]: l += 1 r -= 1 else: if d: return False else: ...
b8d01e47ea55102d1e7fa3e0678f9958e5fe6646
wonggamggik/algorithm_solving
/dongbin_book/chap6_sort/counting_sort.py
580
3.671875
4
import random def counting_sort(data): sorted_data = [] count = [0] * (max(data) + 1) for i in range(len(data)): count[data[i]] += 1 for i in range(len(count)): for j in range(count[i]): #print(i, end=' ') sorted_data.append(i) return sorted_data unsorted...
dde655c631a0b2f64b80c17fb3af588a061b2b36
ppap6/fuckleetcode
/01easy/py/二叉树/112.py
1,401
3.8125
4
''' 给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径, 这条路径上所有节点值相加等于目标和。 说明: 叶子节点是指没有子节点的节点。 示例:  给定如下二叉树,以及目标和 sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1 返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2。 ''' # Definition for a binary ...
b1a63d379e2c5465a55c22182a95ca13d0e92d1e
ShawnSunVip/python-collection
/1_base/06_range_demo.py
339
3.921875
4
# 功能描述 range # by Shawn # 开发时间: 2021/7/22 16:56 #range(start,stop,step) r1=range(10) #[0,1,2,3,4,5,6,7,8,9] 从0-10不包括10 步长1 print(list(r1)) r2=range(1,10) #[1, 2, 3, 4, 5, 6, 7, 8, 9] 从1-10不包括10 步长1 print(list(r2)) r3=range(1,10,2) #[1, 3, 5, 7, 9] 从1-10不包括10 步长2 print(list(r3))
247a2516239b122c4b7039cd5b3fb11d057125a0
mingrener/mygit
/learnPython/python基础-01/08-打印矩形.py
91
3.8125
4
i = 1 while i<=5: j = 1 while j <= 5: print("*", end="") j = j+1 i = i+1 print("")
0feccedceefb8de8431b98e39397551898411646
lguilhermefp/advanced-python
/classes/objects_strings.py
651
3.734375
4
class Person(): def __init__(self): self.fname = "luis" self.lname = "guilherme" self.age = 20 def __repr__(self): return "<Person Class - fname: {0}, lname: {1}, age: {2}".format( self.fname, self.lname, self.age ) def __str__(self): return "Person ({0} {1} is {2})".format( self.fname, self...
9f25d0c34f79f4eac35dcb750d33414b4cd88c88
evg-mar/nlp-util
/levenstein_distance.py
3,046
3.71875
4
# -*- coding: utf-8 -*- """ @author: evgeniy Implementation of the Levenstein and Edit distances. Levenstein: remove + add = exchange of a letter costs 2 Edit: remove + add = exchange of a letter costs 1 """ import numpy as np #dummy value for the Levenstein/Edit distance matrix dummyval = -1 def strDistance(...
0c647f644c0164b227c72cd7e33f59586e39a712
SamvRoosmalen/Master-Mind-Project
/Structured programming/1a/Compressie.py
376
3.5625
4
def compression(file): new_file = "" with open(file, "r") as f: for line in f: no_spaces = line.replace(" ", "") new_file += no_spaces f.close() new_file = new_file.replace("\n", "") with open(file, "w") as f: f.write(new_file) f.close() ...
bc15db5ff2eafa5785f2e8baea6295dfefa0cf6a
RajanIsBack/Python_Codes
/factorial.py
321
4.1875
4
'''find factyorial of any number''' factorial=1 user_input=int(input("Please enter positive discrete number whose factorial you want to know")) user_input1=user_input while (user_input !=1): factorial=int(user_input)*int(factorial) user_input =(user_input -1) print("factorial of",user_input1,"is",factorial) ...
e73ac827abf2381c3aeeefacff2e095a6f70be10
cirino/python
/CursoGuanabara/ex24_aula09_guanabara.py
311
3.90625
4
print(""" Exercício 24 da aula 09 de Python Curso do Guanabara Day 7 Code Python - 06/05/2018 """) cidade = str(input('Qual cidade você nasceu: ')).strip() #a primeira é "santo" print(cidade.lower().split()[0] == 'santo') #a primeira começa com "santo..." print(cidade[:5].lower() == 'santo')
93c784f492a37d97d1052fe217101b7757293e0b
kapsali29/detect_language
/process_input.py
1,675
3.5625
4
from nltk.corpus import stopwords from nltk.tokenize import RegexpTokenizer import operator def utf8len(snippet): """ Return snippet's size in kbytes :param snippet: text :return: snippet's size in kb """ return len(snippet.encode('utf-8')) * 0.001 def read_snippet(filepath): """ The...
4e77e8a56ca9fbd7adce3f4b629ad3de039c9fae
Omkar02/FAANG
/G_OA_05_SmallestDiff.py
1,169
3.796875
4
import __main__ as main from Helper.TimerLogger import CodeTimeLogging fileName = main.__file__ fileName = fileName.split('\\')[-1] CodeTimeLogging(Flag='F', filename=fileName, Tag='Array', Difficult='Medium') # Given an array A of integers, for each integer A[i] we need to choose either x = -K or x = K, and # add x...
a0f51710ddc7b4e5e7cf52b74f3ca828142ea8bc
alexandraback/datacollection
/solutions_5631989306621952_0/Python/haxby/word.py
454
3.5
4
def last_word(word): if len(word) < 1: return "" if len(word) == 1: return word a = word[0] sol = a for i in word[1:]: if i < sol[0]: sol = sol + i else: sol = i + sol return sol n = int(raw_in...
664f94d436b56822b2a9a310ceb1b538c96292c0
JINHYUCK-r/academy
/학원수업/20200720.py
5,895
3.515625
4
20200720 # Tkinter이용 계산기 만들기 from tkinter import * window = Tk() window.title('계산기!!') #창제목 top_row = Frame(window) # Frame : 다른 위젯들을 그룹핑하는데 사용 (계산결과가 나오는 화면) top_row.grid(row=0,column=0) #가로 0번줄, 세로 0번줄. 맨위에 표시되는 의미 display = Entry(top_row, width=33, bg='light green') # Entry : 한줄의 텍스트를 입력받는다. ...
d0c3a52add6fc0da330235b03a4d13cd069c1146
dpflann/Project_Euler
/pe1/pe1.py
422
4.25
4
#!/usr/bin/python # iIf we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. # # Find the sum of all the multiples of 3 or 5 below 1000. def sumOfMultiples(): return sum(set(filter(lambda n: n % 3 == 0 or n % 5 == 0, range(1, 1000)))) def so...
f7abcc56947c4f041c8ed0a3c1ce79ecc6d3e6be
JeffreyDantas/Aprendizado
/Exercícios Python Curso Em Vídeo/ex090.py
556
3.90625
4
#Faça um programa que leia nome e média de um aluno, guardando em um dicionário. #No final, mostre o conteúdo da estrutura na tela. #E diga se o aluno foi ou não Aprovado! dados = {} dados['nome'] = str(input('Nome: ')) dados['Média']= float(input(f'Média de {dados["nome"]}: ')) if dados['Média'] >= 7: resultado = ...
1978cdaec894f1f8966b8b2f4702f3fc2f7cd330
LukaszSikorski/Raport_Algorytmow
/src/Executor.py
1,419
3.5
4
import time import threading import multiprocessing import copy class Executor: def __init__(self,algorithm,data: list): self.algorithm = algorithm self.data = copy.deepcopy(data) self.deltaTime:float=float() def execute(self): start= time.perf_counter() result=...
ba33dc8a98cdf25aba1811597f1d8c9f3a2ed5ff
nirajbawa/python-programing-code
/11_python.py
3,530
3.53125
4
# # 1. # class c2dvec : # def __init__(self, i, j): # self.icap = i # self.jcap = j # def __str__(self): # return str(self.icap) + str(self.jcap) # class c3dvec(c2dvec): # def __init__(self, i, j, k): # self.kcap = k # def __str__(self): # return s...
3c291ab4e5ce6b624d0cf1c92717b81cf744c803
python4humanities/book
/정리하기 스크립트/4.6 원하는 텍스트만 추출하기/06.py
414
3.71875
4
import re text = 'An apple is my favorite thing' pattern0 = re.compile('^apple') # 문자열 왼쪽 끝의 'apple'과 일치 pattern1 = re.compile('thing$') # 문자열 오른쪽 끝의 'thing'과 일치 pattern2 = re.compile('apple|banana') # 문자열의 'apple'이나 'banana'와 일치 print(re.findall(pattern0, text)) print(re.findall(pattern1, text)) ...
271958d26bcd617d4fb83ce49299086df92139e7
Lexxeous/py_house_treasure
/py_house_treasure.py
4,675
3.921875
4
#!/usr/local/bin/python3 # coding: utf-8 """ Title: py_house_treasure.py Author(s): Jonathan A. Gibson Description: Goals: 1. Be able to play multiple different house maps. Store all in "maps" directory with set CSV info to import. 2. Let user choose the house map at the command line, or choose to play a random ma...
24db75bf47d0cf7fdd766f0f579b7b4dac0d1335
fqx9904/Python_Game_Autoplay_Strategy--CSC148
/miscellaneous/blabla/strategy.py
623
3.78125
4
"""strategy module""" from typing import Any import random # TODO: Adjust the type annotation as needed. def interactive_strategy(game: Any) -> Any: """ Return a move for game through interactively asking the user for input. """ move = input("Enter a move: ") return game.str_to_move(move) # TODO...
568054b28958c1b9cf610795e9fe34b946866ec7
RajeshA76/EdyodaPracticeArena
/List And Tuples/Create_list_from_string.py
595
4.25
4
#!/usr/bin/env python3 """ You will have number or elements and next n lines containing list elements. You have to create list from that given string. Input Format: In first-line it will have an integer (numbers of elements inside a list). In the second line, it will have a string containing space separated list elem...
551db9d4084ca97eb48395368f9cdfd2e26d2fbb
touhiduzzaman-tuhin/python-code-university-life
/Separare/155.py
184
3.78125
4
def gen(n): i = 0 while i < n: yield i i += 1 x = gen(20) for i in x: print(i) print("\n") print("\n") for i in x: print(i) print(x.__next__())
0da773c74862931ea8049aed4f7fd402d7bda309
TheMiracleMango/Physics-Calculator
/PhysicsCalculatorV0.py
1,702
4.125
4
# This program uses Physics formulas to calculate missing variable # from sympy import * def calculation (expr = [], symbol_list = []): userInput = [j for j in input('Enter [{0}]: '.format(', '.join(str(i) for i in symbol_list))).split()] for counter in range(len(userInput)): if (userInput[co...
b15ad1abfa1e89b72b14311ce3435dcf6f5a67cb
geediegram/parsel_tongue
/Olatoye/weird_conditionals.py
183
4.0625
4
def weirdo(): number = int(input("Enter your number: ")) if(number % 2 != 0 or (6 <= number <= 20 and number % 2 ==0)): print("Weird!") else: print("Not Weird!") weirdo()
a401e018843ea55c04767f9f0ad96df25a649403
sidamarnath/CSE-231-Projects
/proj06.py
15,103
3.84375
4
###################################################### # Project #6 # Algorithm # Design a basic poker game ###################################################### import cards def less_than(c1,c2): '''Return True if c1 is smaller in rank, True if ranks are equal and c1 has a 'sm...
845aeba8a35852d724d3a9afc3b0a2960ae8f4bf
KevinMichaelCamp/Python-HardWay
/Algorithms/Chapter4_Strings/16_Common_Suffix.py
675
3.859375
4
# Write a function that, when given a word array, returns the largest suffix (word-end) that is common to all words in the array. For inputs ['deforestation', 'citation', 'conviction', 'incarceration'] return "tion". For ['nice', 'ice', 'baby'] return none. import os def commonSuffix(list_of_strings): reversed_st...
ec8eb237880d8f5e02794c8fc9e3a872f9918590
skyla2692/DataStructue
/3.doubly_linked_list.py
4,584
3.734375
4
# 1. class Node 선언 부분 class Node: def __init__(self, key=None, value=None): self.key = key self.value = value self.prev = self self.next = self def __str__(self): return str(self.key) # 2. class DoublyLinkedList 선언부분 class DoublyLinkedList: def __init__(self): self.head = Node() # dummy 노드로만 이루이진 빈...
b032931d817f0fb22705e399e27d1563e8f698ed
ChuhanXu/LeetCode
/jiuzhang/DFS/TSP.py
1,650
3.921875
4
# 给 n 个城市(从 1 到 n),城市和无向道路成本之间的关系为3元组 [A, B, C](在城市 A 和城市 B 之间有一条路,成本是 C) # 我们需要从1开始找到的旅行所有城市的付出最小的成本。 # Example 1 # # Input: # n = 3 # tuple = [[1,2,1],[2,3,2],[1,3,3]] # Output: 3 # Explanation: The shortest path is 1->2->3 # 建图 # {1: {1: inf, 2: 1, 3: 3}, 2: {1: 1, 2: inf, 3: 2}, 3: {1: 3, 2: 2, 3: inf}} ...
c997f991e9b30099f41409725ff53fb98ba3d5e9
daxiangpanda/lintCode
/ 递增的三元子序列 .py
1,238
3.890625
4
# 给定一个未排序的数组,请判断这个数组中是否存在长度为3的递增的子序列。 # 正式的数学表达如下: # 如果存在这样的 i, j, k, 且满足 0 ≤ i < j < k ≤ n-1, # 使得 arr[i] < arr[j] < arr[k] ,返回 true ; 否则返回 false 。 # 要求算法时间复杂度为O(n),空间复杂度为O(1) 。 # 示例: # 输入 [1, 2, 3, 4, 5], # 输出 true. # 输入 [5, 4, 3, 2, 1], # 输出 false. class Solution: # o(n)复杂度 o(1)额外空间 def increasingTripl...
4fc650f3cd9a64cb9d9c63311e56382c05296d60
codingRangerr/practice
/reverse_string.py
135
3.578125
4
def rev_string(str): rev = reversed(str) return rev print(rev_string("Pythonproject")) new = "hello" print(reversed(new))
f0ff84d797d89853ec96f076f343b4865ae5074c
linag99/Proyecto
/FahaCen.py
208
3.515625
4
def calcularCen (): fah = int(input("Digite los grados Fahrenheit: ")) cen = (fah-32)*(5/9)} print ("Los ", fah, "grados Fahrenheit son", cen, " en centigrados.") calcularCen()
fccc728c26d4cf818bef9bd8bfc38e4f1286c8be
juananthony/py-Kmeans
/example1.py
1,003
3.5625
4
import matplotlib.pyplot as plt from PyKMeans import PyKMeans # create the K-means classifier main = PyKMeans() # array of observations points = [[1,1], [1.2,1.0], [1.3, 1.1], [1.8, 0.7], [1.1, 0.7], [0.8, 0.7], [3,3], [3.1,3.0], [3.0,3.1], [3.2,3.7], [2.9,3.4], [9.7,11], [10,10], [10.5,10.7], [10.2,10.1], [-4,-3], [...
e76e08b7d4a9475c99e7f4e3bbe2aa4867ce1788
Mauro-CVO/Python_Programs
/Python_Basico/Conversor_a_pesos.py
303
3.6875
4
## Programa convesor de dolares a pesos mexicanos #Equivalencia del dolar en pesos peso = 0.044 #dolares #Obtener Pesos dolares = input("¿Cuantos dolares (USD) tienes?:") dolares = float(dolares) #Conversión a dolar pesos = round(dolares / peso, 2) pesos = print("Tienes $"+ str(pesos) + " pesos")
3bd2e8ad5d59fd2c2f425711a43faa8e96ad71cb
Matt-J-Jones/Flock-of-Pigeons
/Flock_of_Pigeons.py
5,040
3.984375
4
import random loop=True def reset(): gatheredfood=0 pigeons=20 chicks=10 def huntingforfood(number, location): global surv global dead global food surv=0 food=0 dead=0 while number > 0: if location == "Trafalgar": result = random.randint(1,1...
4e8b0273136d9f1ab642842a442ff9b65ec16fa5
a4lamber/seg1d
/seg1d/examples/ex_segmenter_sine.py
3,130
3.53125
4
''' An example of instancing the Segmenter class to use the convenience methods on array data .. plot:: >>> import seg1d >>> import numpy as np >>> import matplotlib.pylab as plt Then we generate some data >>> x = np.linspace(-np.pi*2, np.pi*2, 2000) #create an array of data >>> targ = np.si...
51e1d40f57d021b15bdba381eb7131322d877a22
TheAlgorithms/Python
/graphs/graph_adjacency_list.py
21,607
3.859375
4
#!/usr/bin/env python3 """ Author: Vikram Nithyanandam Description: The following implementation is a robust unweighted Graph data structure implemented using an adjacency list. This vertices and edges of this graph can be effectively initialized and modified while storing your chosen generic value in each vertex. Ad...
106bcbce59b80feda03b9c08822ea36c69fde801
gabriellaec/desoft-analise-exercicios
/backup/user_051/ch54_2020_09_14_13_07_48_746406.py
293
3.75
4
def calcula_fibonacci(F): lista=[] q=len(lista) i=0 while F>i: if i<2: lista.append(1) i+=1 continue else: a=lista[q-1]+lista[q-2] lista.append(a) i+=1 continue return lista
8005f84ce753898e8a3f52266f71e47494f80b0a
GrearNose/Exercise
/jobHunting/XiaoMiOJ/Median_of_roated_array.py
1,155
3.5625
4
def solution(line): """ Given a str of comma separated numbers of a rotated array, find out its meidan. N.B. length rotated array is odd and all elements are unique. """ nums = [int(x) for x in line.split(',')] # print('nums:', nums) if 1 == len(nums): return nums[0] ...
1f4b3b25ad01bedd496e185c524197afd8f6e030
PlatziMaster/class-python-02
/regex_email.py
276
3.546875
4
import re def run(): email_pattern = re.compile(r'^[a-z0-9_]+@[a-z]{1,10}\.[a-z]{2,10}$') email = input('Enter an email: ').strip() if email_pattern.match(email): print('Valid') else: print('Invalid') if __name__ == '__main__': run()
22044dc10f4e9c1e5a0d576392cbb8798edb1e43
Erick-ECE/ProblemSolving
/leetcode/array/containsDuplicates.py
157
3.5625
4
#contains duplicates #given an array retur T | F if the rray contains duplicates def containsDuplicates(arr): ndup=set(arr) return list(ndup) != arr
83bc24e72031c945f0864b605d4035a03253fcb5
HollyLucky/tenserflow
/test2.py
2,205
3.8125
4
from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf mnist=input_data.read_data_sets("MNIST_data",one_hot=True) print(mnist.train) #我们通过操作符号变量来描述这些可交互的操作单元,可以用下面的方式创建一个: x=tf.placeholder(tf.float32,[None,784]) #x不是一个特定的值,而是一个占位符placeholder,我们在TensorFlow运行计算时输入这个值。我们希望能够输入任意数量的MNIST图像,每一张图...
5f8bf5e81cf7a4f31fdd615f16e9e522acbc5102
emreozdem/University
/First Semester/RecursionPython/quiz5-1.py
467
4.0625
4
def diamond(number, number2, direction): if number2 == number: # for mid to down direction = 0 if number2 != 0: print(" "*(number-number2)+ "*"*(number2*2-1)+ " "*(number-number2)) if direction == 1: diamond(number, number2+1, direction) # up if direction == 0: diamond(number, number2-1, direction) #...
0b409f5c4347fdae805908e294ea08c9e36f81da
gvnaakhilsurya/20186087_CSPP-1
/cspp1-assignments/m5/p3/p3/square_root_bisection.py
618
3.59375
4
''' # using approximation method @author:gvnaakhilsurya # testcase 1 # input: 25 # output: 4.999999999999998 # testcase 2 # input: 49 # output: 6.999999999999991 ''' def main(): ''' # epsilon and step are initialized # don't change these values ''' x_num = int(input()) epsilon = 0.01 lower...