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
d985c8b5d31ddcc52354971e6be32cf3cc6048f7
Hapachino/dateFormat
/dateFormat.py
704
3.84375
4
#! python3 # dateFormat: Finds all file names in a folder, revises American-style dates to European-style dates import os, re, shutil # Create a regex that can identify the text pattern of American-style dates. dateRegex = re.compile(r''' (0[1-9]|1[0-2]) # Month - (10|20|[0-2][1-9]|3[01]) ...
85b9bec9a1ceea4ee661b59c7efc82595e30f871
Anand8317/food-ordering-console-app
/admin.py
2,127
4.15625
4
admin = {"admin":"admin"} food = dict() def createAdmin(): newAdmin = dict() username = input("Enter username ") password = input("Enter password ") newAdmin[username] = password if username in admin: print("\nAdmin already exist\n") else: admin.update(newAdmin) ...
837be113dd5121f2a971d7f2b17c96095ea7130f
kamau96/Search2DMatrixII
/main.py
1,297
3.6875
4
class Solution: def searchMatrix(self, matrix, target: int) -> bool: low = 0 high = len(matrix[0]) - 1 mid = (high - low) //2 + low # reduce matrix by half at every iteration of row for row in range(len(matrix)): if matrix[row][mid] > target: ans =...
72f8176eba0fa00481ac5a7dd35bfacf9f195d36
x415a/GB_py_algorithms
/lesson_1/task_8.py
347
4.03125
4
# Определить, является ли год, который ввел пользователь, високосным или не високосным year = int(input("Введите год: ")) if not year % 400 or not year % 4 and year % 100: print("Год високосный") else: print("Год не високосный")
2b25c12af8bc325692f87185b620c4e92d61c203
x415a/GB_py_algorithms
/lesson_1/task_3.py
601
3.890625
4
# По введенным пользователем координатам двух точек вывести уравнение прямой вида y = kx + b, проходящей через эти точки x1, y1 = map(float, input("Введите координаты точки (X Y): ").split()) x2, y2 = map(float, input("Введите координаты 2-ой точки (X Y): ").split()) if x1 == x2: print("Координаты X двух точек со...
905ebdae897de9ad5ddf91f182b18dbd8d74734d
eaton-lab/seedcount
/src/processing.py
2,302
3.625
4
#!/usr/bin/env python """ DATA processing for seedcount app """ import os import pandas as pd # get file from absolute path relative to here. SEEDS = os.path.join(os.path.dirname(__file__), "SEEDS.csv") class SeedData: def __init__(self): # the full dataset self.data = pd.read_csv(SEED...
c7465905bf69a777d15c7493cd30edcac6d9a46b
bowenowen/IHATETHIS
/Vector2.py
1,159
3.859375
4
import math class Vector2: def __init__(self, x, y): self.x = float (x) self.y = float (y) self.magnitude = math.sqrt (x**2 + y**2) def __repr__ (self): return str ((self.x, self.y)) def __add__(self, other): return Vector2(self.x + other.x, self.y + other.y) ...
a15dfce037393ec1b87677d8a7ffb6671fe73ccb
TomMonks/mcts-cartpole
/tictactoe.py
1,653
3.59375
4
from abc import ABC, abstractmethod import numpy as np class GameEnvironment(ABC): @abstractmethod() def step(self, action): ''' Returns: -------- Tuple new_state, reward, done, info ''' pass class TicTacToe(GameEnvironment): def __init__(self...
48b95d1ce551f0186bce02832725ed39911af162
srihari4mbatech/High_performance_python
/Iterators.py
314
3.546875
4
def range(start, stop, step=1): numbers = [] while start < stop: numbers.append(start) start += step return numbers def xrange(start, stop, step=1): while start < stop: yield start start += step for i in range(1,10000): pass for i in xrange(1,10000): pass
0fcbf0c6e14266c8194b890a57fda39bff59e58a
deep12030/Python_Test
/venv/p6.py
78
3.671875
4
l=[2,3,4,5,5] doubles=[] for item in l: double.append(2*item) print(l)
e61302dc77a810b6495e3462aa71264b0adaced3
deep12030/Python_Test
/continue.py
74
3.796875
4
for j in range(5): if j==3: continue print("count", j)
d351efdb3b29116254e57313060815bb13e39713
deep12030/Python_Test
/search.py
111
3.75
4
arr=[3,4,5,6,7,8,83] for i,j in enumerate(arr): if j==8: print (i) print(j) break
c9033580121ba38277facb1729565d15a994b8b6
Ani-Stark/Python-Projects
/reverse_words_and_swap_cases.py
419
4.15625
4
def reverse_words_order_and_swap_cases(sentence): arrSen = sentence.split() arrSen = list(reversed(arrSen)) result = list(" ".join(arrSen)) for i in range(len(result)): if result[i].isupper(): result[i] = result[i].lower() else: result[i] = result[i].upper() ...
548baf911844ed52dfb3e65ecd0c225ad23100f3
zaedulislam/Machine_Learning_A-Z_Hands-On_Python_and_R_In_Data_Science
/Part 7 - Natural Language Processing/Natural Language Processing.py
3,349
3.828125
4
# Natural Language Processing # Step 1 - Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Step 2 - Importing the dataset filepath = 'Dataset/Restaurant Reviews.tsv' # We need to add some additional parameters to specify that we are importing .tsv file # "delimiter" s...
b6a3f5c43e28a593bce08caae98b22548ebc85d0
nmichiels/adventofcode2020
/day3/day3.py
1,015
3.96875
4
import numpy as np # https://adventofcode.com/2020/day/3 def load_map(file): map = [] lines = file.readlines() for line in lines: # print(line) line = [char for char in line] line = line[:-1] map.append(line) return np.asarray(map) file = open('input.txt',...
e0857fdba34db0f114bcf7843f844aea775303e7
Villanity/Python-Practice
/Reverse Array/Reverse_Array_while.py
343
4.59375
5
#Python program to reverse the array using iterations def reverse_array (array1, start, end): while (start<=end): array1[start], array1[end] = array1[end], array1[start] start += 1 end -= 1 A = [1, 2, 2 , 3, 4] start=0 end= len(A) -1 print(A) print("The reversed Array is: ") reverse_array(A...
e1b54f773e836e5508ad935765be9c56f13c5d91
rashmika13/sei
/w07/d2/python-control-flow/exercise-instructor.py
1,022
4.21875
4
# color = input('Enter "green", "yellow", "red": ').lower() # while color != 'quit': # print(f'The user entered {color}') # if color == 'green': # print('Go!') # elif color == 'yellow': # print('Slow it doooowwwwnnnnn') # elif color == 'red': # print('Stop!') # else: # ...
8b3c2346c2173ddeb645d9e2174861f19a1eebc9
geek-log/pyboom
/p05/bomba.py
254
3.828125
4
# Boom!!! def conteo(segundos): if segundos < 1: print('No puedo contar menos de un segundo.') else: for segundo_actual in reversed(range(1, segundos + 1)): print(segundo_actual) print('BOOM!!!') conteo(10)
f6b350f23b5463bbe92f8530e2a75150507a3195
ralsina/python-no-muerde
/codigo/1/deco1.py
257
3.765625
4
# -*- coding: utf-8 -*- import random def f1(): print 'Estoy haciendo algo importante' def f2(): print 'Estoy haciendo algo no tan importante' def f3(): print 'Hago varias cosas' for f in range(1,5): random.choice([f1,f2])() f3()
6b048c360fde7f3208d5518bbd4a085f69a4a63b
nsmryk/google-step-tsp
/solver_mine.py
3,657
3.875
4
#!/usr/bin/env python3 import sys import math import copy from common import print_tour, read_input, format_tour INF = 100100 def distance(city1, city2): return math.sqrt((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2) ''' Makes matrix whose element means distance of cities using distance() Input cities ...
65751f4d907bcaecb83938e7b0421431a90c179c
thomaswel/javazero-compiler
/Semantics.py
4,431
3.765625
4
''' Student: Thomas Welborn Class: 4316 Compiler Design and Construction Purpose: This program utilizes takes the quads from the Syntax Analysis and forms the equivalent assembly code which is then written on the output file called 'assembly_temp.txt'. This assembly Code is then fed to the Cod...
07c27f90291b2917d32a72575850c2d524eb3edd
dfunction/dog
/SimpleTimer.py
609
3.859375
4
import time class SimpleTimer: def __init__(self): self.started = False self.time = -1 def start(self): if( not self.started): self.time = time.time() self.started = True return("Started timer.") else: print("Warning! Already sta...
d5c73b78968c0875b4cffbef04178b552ac28046
aschwartz5352/Homework4
/function_checks.py
4,042
3.828125
4
import numpy as np class Cache(object): def __init__(self, A=None, W=None, Z=None): self.A = np.copy(A) self.W = np.copy(W) self.Z = np.copy(Z) # Description: Computes affine transformation Z = AW + b. # Inputs: Incoming batch of data A (2d array of size n x d), layer weight W (2d array ...
83df939922a51537d41ff6da79430deb53de1f7a
nmaruthi/scribble
/pd_csv_df.py
432
3.8125
4
import pandas as pd #Reading a CSV file brics=pd.read_csv(data_sets_path+separator+'brics.csv', index_col=0) #Subsetting the data frame to specific rows & columns #This returns a data frame since double-square brackets are used brics.loc[['RU', 'IN', 'SA'], ['country', 'capital']] #Fetch all rows, specific columns b...
5b02ba9aa93c4a55dc78596dbbf324133b6c2d86
nshah59/school_work
/Final Project (2).py
3,219
3.609375
4
#!/usr/bin/env python # coding: utf-8 # PCA for Removing Risk From a Portfolio # By Nikhil Shah, Parsh Jain, and Bhaardwaj Vemapulli # In this research project, we are going to use PCA to remove some of the variation in a portfolio over time, creating a more "market-neutral" portfolio. It has been determined that by ...
fb67e1eff16e1804ecf9c2e4ff0010962bb930c3
guyitti2000/int_python_nanodegree_udacity
/lessons_month_one/lesson_3_FUNCTIONS/test.py
263
4.21875
4
def times_list(x): x **= 2 return x output = [] numbers = [2, 3, 4, 3, 25] for num in numbers: val = times_list(numbers) print(output.append(val)) # this is supposed to iterate through a list of numbers then print out the squares
03666e9744d284828ae0e1f3d17aeadf22d4b96a
guyitti2000/int_python_nanodegree_udacity
/neos_project/workspace/write.py
2,831
3.640625
4
"""Write a stream of close approaches to CSV or to JSON. This module exports two functions: `write_to_csv` and `write_to_json`, each of which accept an `results` stream of close approaches and a path to which to write the data. These functions are invoked by the main module with the output of the `limit` function a...
093d56467f6309b099b8e2210efe8ecaca8397eb
shanahanben/myappsample
/Portfolio/week6/article_four_word_grabber.py
564
4.15625
4
#!/usr/bin/python3 import random import string guessAttempts = 0 myPassword = input("Enter a password for the computer to try and guess: ") passwordLength = len(myPassword) while True: guessAttempts = guessAttempts + 1 passwordGuess = ''.join([random.choice(string.ascii_letters + string.digits)for n in ...
a59f277d6b93bf3028023a14af63c1249e9ac575
athreyaanand/vile
/py_files/Individual/DNA.py
1,017
3.5625
4
import random class DNA(object): def __init__(self, dna): self.dna = dna self.MUTATE_RATE = .125 self.genes = dna.split(':') self.traits = ["Gender", "Height", "Weight", "Eye Color", "Skin Color"] def get_gene(self, trait): return self.genes[self.traits.index(trait)] def cross(self, otherD...
360b36c700983e8cddb0049dded9d78abe12b75a
steve-ryan/python-tutorial-for-beginners
/list.py
1,226
4.1875
4
name = ['ken','sam','antony'] list("wachira") # split print("hello am steve wachira." .split("ac")) # print name # print test # adding list cuzo = ['shifrah','shikoh'] cuzo.append('bilhah') print(cuzo) #add list .insert() test_point = [90,87,17,56] test_point.insert(1,50) print(test_point) #extend test_point = [90,...
759e6a8150e36d65c3ab7acfc86348b3e77f1a3e
abernatskiy/sparsModGECCO2015
/eswclientMedium/parseStr.py
323
3.546875
4
import numpy as np def parse1d(string): return np.array(map(int, string.split(' '))) def parse2d(string): arr = parse1d(string) size = np.sqrt(len(arr)) if not size.is_integer(): raise ValueError('String parsing failed: the string does not encode a square matrix') size = int(size) return arr.reshape(size, siz...
7202d29cd1b581adc9caf12772ecea6cff3dbced
VS1945/Test_Python
/function2_loops.py
2,295
3.65625
4
"""def intersect(*args): res = [ ] for x in args[0]: # Сканировать первую последовательность for other in args[1:]: # Во всех остальных аргументах if x not in other: break # Общий элемент? else: # Нет: пре...
89ef20c0a13438ae826d76f954cf4382f36f4795
morskiq123/Python-Library-Management
/booksearch.py
5,505
3.609375
4
#Library system #By Angel Yotov #Began 01.12.2018 #Finished 12.12.2018 ## This is the module that is used for looking up the desired books from tkinter import * from tkinter import ttk from tkinter import messagebox def titleBookSearch(arg = None): ## Function used to search for the books via Title, accesses dat...
0239e6879a00b654f101431592f118095cc8d569
Taelar/FastaCompressor
/utils.py
1,109
3.8125
4
# Global constants definition A = "A" C = "C" G = "G" T = "T" # Returns the reverse complement of the given string def reverseComplement(data: str) -> str: result = "" for char in data[::-1]: result += charComplement(char) return result # Returns the complement of the given char, if a string is ...
1567300876482b54b27e3b4df9e451903f16241f
lk90/leet_code
/leet14_longest_common_prefix.py
759
3.5625
4
""" """ """ class Solution: def longestCommonPrefix(self, strs) -> str: if len(strs) < 1: return "" prefix = min(strs, key=len) for i, j in enumerate(prefix): for common in strs: if common[i] != j: return prefix[:i] retur...
d66782a922ea7dbf9efcbd882157a393d5680536
josephjlee/bucketlist
/bucketlist/appmanager.py
2,434
3.546875
4
"""This module creates a new user instance and stores it in an in-memory disctionary.""" import random from bucketlist.models import User class ApplicationManager(): """creates """ def __init__(self): self.users = dict() # use indexing to map user_id to email self.__index = dict() ...
bcc8bb41e222e24978b48956e4ad4d2239af9240
Anton-py-dev/Fitnes
/PersonList.py
928
3.609375
4
import pickle from Fitnes.Person import Person class PersonList: def save(self): with open("p.bin", "wb") as f: pickle.dump(self.list, f) def newUser(self, name, weight): self.list.append(Person(name, weight)) def choseUser(self): # замість цієї функції буде функ...
d2e6f36aa3d71c3f0013b42ebe3a8044723e9d8e
tmcg/AdventOfCode2017
/src/advent07.py
2,704
3.921875
4
# Puzzle 7: Recursive Circus # http://adventofcode.com/2017/day/7 class Program: def __init__(self,name,weight,childNames): self.name = name self.weight = weight self.childNames = childNames self.parent = None self.children = [] class Advent07: def __init__(self, tower_programs = None): p...
c71d8a0cdd75f44d9ea7db1429deb0f678d0e275
stephengao0121/SI231-project
/mtx2csv.py
2,112
3.6875
4
''' convert mtx file to csv author: panxq email: panxq@shanghaitech.edu.cn ''' import argparse import numpy as np import pandas as pd import scanpy def set_parser(parser): ''' Set the parser Keyword Arguments: parser - argparse.ArugumentParser type, parser to be set ''' parser.add_argume...
41418bb0f9eff2383736a2a5a8f9278264b56433
makhmudislamov/pythonExercism
/raindrops/raindrops.py
551
4.03125
4
def convert(number): pling = number % 3 plang = number % 5 plong = number % 7 if pling == 0 and plang == 0 and plong == 0: return("PlingPlangPlong") elif pling == 0 and plang == 0: return("PlingPlang") elif plang == 0 and plong == 0: return("PlangPlong") elif p...
c11856d3db5aeedb54926307e060d905ba14fdb2
Slam4you/gramma_check_dictionaries
/check.py
630
3.78125
4
check_list = [] errors_list = [] for i in range(int(input("Введите кол-во слов которые хотите задать для проверки, после введите их"))): string = input().lower().split() for i in string: check_list.append(i) print(check_list) for i in range(int(input("Введите кол-во строк которые хотите проверить, посл...
fa31392f07b364bfa09620747b01ea5267c92582
Edgineer/Los_Angeles_Parking_Citations
/scripts/coordDistanceCalculator.py
782
3.5
4
import argparse import math #Add two coordinates as command line arguments #ex. python coordDistanceCalculator latP1 lonP1 latP2 lonP2 parser = argparse.ArgumentParser(description="Get distance (Km) between two WGS84 Coodrinates") parser.add_argument('lat1',type=float,help="la1") parser.add_argument('lon1',type=float,...
08429c4b38cc85eac8a525b900fa763410fdd6e9
mas250/Python2
/2_7_c_program_flow.py
408
3.625
4
#This program models the flow of information in a program number1 = 10 number2 = number1 print "number1 contains", number1, "and" print "number2 contains", number2 number2 = number2* 10 print "Now number2 contains", number2 number1 = 2 * number2 print "Now number1 contains", number1 Sum = number1 + number2 print ...
55fbd522dd89a2d6e0a5c36bb7d0a24d86035055
mas250/Python2
/6_8.py
393
3.71875
4
# -*- coding: cp1252 -*- print "This program will tell you how many years it will take for the" print "population of Uganda to exceed 50 Million \n" population = 26000000 years = 0 while population < 50000000: growth = population * 6/100.0 population = population + growth years = years + 1 print "It will...
8ba4366a258385b21040ca1086672487ee56a5a3
mas250/Python2
/3_7.pyw
222
3.953125
4
#exchange pounds to dollars print "This program will convert pounds to dollars" pounds = input("Enter an ammount of pounds : ") dollars = pounds*1.79 print print "the ammount of dollars is: $%0.0f" % (dollars) print
1dc54c81a70468cbfbf82104e174b124d6db69f3
neosupar/python
/Module1/variable.py
189
4.0625
4
a = 'mukund ' b = 'is good person' print(a,b) # it will pick the last value which you have assigned x = 1 x = 2 x = 3 print(x) # the above behaviour is called dynamically types language
3efa9ff42e4a8ed0f45f8d6c521b1df357116ac8
cheerhou/PythonPlayGround
/guessWordGame.py
1,546
3.671875
4
import time # 每组队伍的游戏过程 def guess(word_group): correct = 0 start = time.time() for k in range(len(word_group)): # 显示词语, 格式化形式拼接字符串 print('%d. %s' % (k + 1, word_group[k])) flag = input('请答题,答对请输入y,跳过请输入任意键') sec = time.time() - start # 统计用时 if 50 <= sec <=...
b13646001a397baa28ea5ad865524fc2546e1edb
jembantonio/holbertonschool-higher_level_programming
/0x0B-python-input_output/7-save_to_json_file.py
233
3.671875
4
#!/usr/bin/python3 ''' a function that writes an Object to a text file using a JSON representation ''' def save_to_json_file(my_obj, filename): import json with open(filename, 'w') as file: json.dump(my_obj, file)
27b6d016c81460e3028b4d9bb88019ef91e12f3d
jembantonio/holbertonschool-higher_level_programming
/0x0B-python-input_output/9-add_item.py
497
3.59375
4
#!/usr/bin/python3 ''' a script that adds all arguments to a Python list and then save them to a file ''' import sys import json save_to_json_file = __import__('7-save_to_json_file').save_to_json_file load_from_json_file = __import__('8-load_from_json_file').load_from_json_file items = [] try: items = load_from...
76e001381fbef5ddca81105f6a50932eb44553a0
jembantonio/holbertonschool-higher_level_programming
/0x10-python-network_0/6-peak.py
463
3.9375
4
#!/usr/bin/python3 ''' Find the peak element ''' def peak_binary(arr, low, hi): # if array is empty if low == hi: return arr[low] # find index of middle element mid = low + (hi - low) // 2 # compare middle element with right elements if arr[mid] > arr[mid + 1]: return peak_bin...
366a8b6c6894833b727c48449e68572875542ac0
explorerwjy/jw_anly502
/PS03/wordcount_top10_my.py
1,128
3.875
4
#!/usr/bin/env python2 # This is a version of the wordcount that only prints the top10. # It does so by maintaining a heap as an instance variable in the reducer object. # # The mapper outputs <word,1> # The reducer_init() creates an empty heap # The reducer inputs <word,(1,1,1...)> and outputs NOTHING. # Instead, ...
7ca0f4b1c96818019d9826d39376218d5ef0aa85
explorerwjy/jw_anly502
/PS04/wikipedia_by_month.py
1,579
4.03125
4
#!/usr/bin/spark-submit # # Problem Set #4 # Implement wordcount on the shakespeare plays as a spark program that: # a.Removes characters that are not letters, numbers or spaces from each input line. # b.Converts the text to lowercase. # c.Splits the text into words. # d.Reports the 40 most common words, with the most ...
e4b192d59bbd91253caf229c77b5a33c8d764b73
tajrian-munsha/Python-Basics
/python46 (bitwise operation).py
3,351
4.53125
5
# Bitwise operators # bitwise operators does operations on bits, # it doesn't do operations with the value. # What is bits? # when we convert the values to binary, # the 0's and 1's are called bits. # BTW: # we can convert integers to binary using bin() function. # we can convert binary to integers using int(...
0b4f3e5579bab814d446b9ad2852a353aa146ce7
tajrian-munsha/Python-Basics
/python39 (Duck Typing & EAFP).py
5,872
4.09375
4
# duck typing and asking forgiveness, not permission (EAFP) # in this module, we will go over couple of aspects of being pythonic. # basically, it means we are following conventions and coding style of python language and we need to write clean and readable code. # here we will going to learn basically two concepts of...
de470b30b64ae9a22720d9056bf2c9aeb4973d1a
tajrian-munsha/Python-Basics
/python40 (logging)/employee.py
1,621
3.671875
4
# initial code # import logging # logging.basicConfig(filename="Employee_Log.log",level= logging.INFO, format="%(levelname)s:%(message)s") # class Employee: # def __init__(self,first,last): # self.first=first # self.last=last # logg...
106ddf889cd1ac1fb1b4e6fe1beef995982c4c31
tajrian-munsha/Python-Basics
/python2 (displaying text and string).py
2,391
4.53125
5
# displaying text #to make multiple line we can- 1.add \n in the string or, 2.use print command again and again.\n means newline. print ("I am Shawki\n") #we can use \t in the string for big space.\t means TAB. print ("I am a\t student") #we can use triple quotes outside the string for newline.For doing that,we can ...
0812e177cd0f9b5e766f6f981b4bc1947946fa22
akhilreddy89853/programs
/python/Natural.py
288
4.125
4
Number1 = int(input("How many natural numbers you want to print?")) Count = 0 Counter = 1 print("The first " + str(Number1) + " natural numbers are", end = '') while(Count < Number1): print(" "+str(Counter), end = '') Counter = Counter + 1 Count = Count + 1 print(".")
86d44dfbd51b8ab5916e813f9157c89517d6056a
bhasin11/DataStructures-and-Algorithms-in-Python
/src/findTheDifference.py
935
3.53125
4
class Solution(object): def findTheDifference(self, s, t): """ :type s: str :type t: str :rtype: str """ # The approach is to find the ASCII value of each character of both # the strings. Add the ASCII values of each character of String 't' # to a tem...
e4039d6599b20288fc8772a85ea904cc57895441
bhasin11/DataStructures-and-Algorithms-in-Python
/src/singleNumber.py
645
3.53125
4
class Solution(object): def singleNumber(self, nums): """ :type nums: List[int] :rtype: int """ # The approach is to XOR all elements of the 'nums' array. # with the help of a for loop. It will gradually remove bits # of all elements occuring twice. ...
7ee6a61f275983b4e4b67c9eef5c7cae48941116
nolanbeihl/problemsolving1
/problemsolving1.py
1,182
3.859375
4
#starting on problem sovling 1 word = "Hello" reversed_word = '' word2 = "hello world" how_many = "aaaabbbbcccdddd" for index in range(len(word) -1, -1, -1): reversed_word += word[index] print(reversed_word) first_letter_capital = word2.title() print(first_letter_capital) def compress_string(string): stri...
d8da76f14cc77619d9728df80d3f93e6a6133f7c
tenzinsonam/matcher
/1st/dict.py
868
3.703125
4
def print_dict(given): fd = open(given,"r") fd1 = open("dictfrom","r") fd2 = open("2","w") #line = fd.readline() dict1 = "" #while(line!="}"): #dict1 = dict1 + line for line in fd.readlines(): #print line.strip() dict1 = dict1 + line.strip() + "\n" dict2 = eval(dict1) #print dict1 #print dict2 for li...
9dd3d5b224ba6329d6e24811d550b654cdb81748
km19809/Church
/church/pair.py
788
3.625
4
""" Church encoding of pairs and lists Author: Minsoo Kim<km19809@users.noreply.github.com> """ from typing import Callable from .boolean import Bool, T, F def PAIR(first: Callable, second: Callable) -> Callable: """ Makes two input as a pair """ def inner_pair(selector: Callable): return sele...
86801e9908741b19e507555f1edb72719fcaa015
chris3will/algorithmStudy
/leetcode/783.PY
660
3.78125
4
import math import numpy # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def minDiffInBST(self, root): """ :type root: TreeNode :rtype: int """ res=[] ...
a276ca1af138b5c0cd2237bac8390d5c91f4fb32
ilyanalid/rep1
/w4/task4.py
1,216
3.609375
4
import sys import argparse import math def get_primes(n): lst = [] candidate = 2 while (len(lst) < n): nokey = 1 for j in range(2, int(math.sqrt(candidate+1)+1)): if candidate%j == 0 and j != candidate: nokey = 0 break else: ...
2363bdd68dbef23b937b82cce046974e847c43a4
sunrocha123/Programas_Estudo_Python
/coeficienteBinomial.py
668
4.15625
4
import math # exibição do cabeçalho def cabecalho(): print("===================================") print("CÁLCULO DO COEFICIENTE BINOMIAL") print("===================================") print('') # cálculo do coeficiente binomial def coeficienteBinomial(n, p): calculo = math.factorial(n)/(math.fac...
c242a7dda5d51b92447258e2d5f3bbe81896957e
sunrocha123/Programas_Estudo_Python
/SomaDigitosDeUmNumero.py
520
4.0625
4
numero = input("Digite um número inteiro: ") i = 0 numeroAlterado = 0 soma = 0 while i <= len(numero): if i == 0: RestoDivisao = int(numero) % 10 DivisaoInteira = int(numero) // 10 numeroAlterado = DivisaoInteira soma = soma + RestoDivisao i += 1 pass else: ...
3b41b035eacc4635942782b16a3a97fe8e7b73a6
sunrocha123/Programas_Estudo_Python
/DistanciaDoisPontos.py
524
3.84375
4
N1 = float(input('Digite o 1º número: ')) N2 = float(input('Digite o 2º número: ')) N3 = float(input('Digite o 3º número: ')) N4 = float(input('Digite o 4º número: ')) #N1 e N2 são as coordenadas do ponto 1 no plano cartesiano #N3 e N4 são as coordenadas do ponto 2 no plano cartesiano #ponto 1 x1 = N1 y1 = N2 #pont...
8405ced9e1bbe1a143024b3977535e3ff26acee8
sunrocha123/Programas_Estudo_Python
/tamanho_da_matriz.py
339
3.921875
4
def dimensoes(matriz): '''Esta função tem como objetivo, exibir ao usuário o número de linhas e colunas que possui a matriz digitada''' lin = len(matriz) # nº total de linhas col = len(matriz[0]) # nº total de colunas print(str(lin) + "X" + str(col)) minha_matriz = [[1,2],[3,4],[3,9]] dimensoes(...
7a9ed1b59eca36822827d20359aa1b1eb9292d52
JeRusakow/epam_python_course
/homework7/task2/hw2.py
1,861
4.4375
4
""" Given two strings. Return if they are equal when both are typed into empty text editors. # means a backspace character. Note that after backspacing an empty text, the text will continue empty. Examples: Input: s = "ab#c", t = "ad#c" Output: True # Both s and t become "ac". Input: s = "a##c", t = ...
f226cabe15ea1b978dcb8015c040575394d90fbf
JeRusakow/epam_python_course
/tests/test_homework1/test_fibonacci.py
1,083
4.125
4
from homework1.task2.fibonacci.task02 import check_fibonacci def test_complete_sequence(): """Tests if true sequence starting from [0, 1, 1, ... ] passes the check""" test_data = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] assert check_fibonacci(test_data) def test_sequence_fragment(): """Tests if tru...
02e9cfff62b64f15094210ba0d8fb51e555afd2e
billydh/python_data_structure_and_algorithm
/LeetCode/easy_problems/leetcode_maximum-depth-of-binary-tree.py
627
3.75
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 maxDepth(self, root: 'TreeNode') -> 'int': if root is None: return 0 left = self.maxDepth(root.left) right...
43ce08c0309abc36313fd76338195f658e5f8851
arevish/palindrome
/palindromifylist.py
1,355
3.71875
4
n=input("Enter your list seprated by ',' ").split(",") print(n) li=[] for i in range(len(n)): p=n[i][::-1] if n[i]==p: # print(f"{n[i]} is a palindrome") li.append(int(n[i])) else: # print(f"{n[i]} not a palindrome") # find next palindrome p=p[::-1] ...
aea048e3a4e9971ee878e5091519a9e2cae59d50
vermuz/PythonAdvancedProgrammingTopics
/IterationGenerators.py
8,113
4.625
5
#! /usr/bin/python # e-satis @ stackoverflow: http://stackoverflow.com/questions/231767/the-python-yield-keyword-explained # Iteration : Going over items in a list, one-by-one myList=[1,2,3] for i in myList: # "for X in Y" is an iteration pattern print i, print # The retrieval of the next item using the iterato...
3f0c4cd2a263b89ae578f6e157a66b0fab49fa6d
viveksyngh/idiomatic-python
/loop.py
2,336
3.953125
4
# Looping over a range of numbers for i in [0, 1, 2, 3, 4, 5]: print i**2 for i in range(6): print i**2 ## Pythonic for i in xrange(6): print i**2 # Looping over a collection colors = ['red', 'green', 'blue', 'yellow'] for i in range(len(colors)): print colors[i] # Pythonic for color in colors...
f120cc35f401403d218377de30136435fb9c29c2
mdakram09/joy-of-computing-using-python
/sum_of_first_n_numbers.py
152
3.953125
4
n=int(input("please enter ther last number : ")) answer=0 for i in range(n+1): answer=answer+i print("sum of first ",i," numbers is ",answer)
a8cb902d310336a7285cd329c56559bf7844d280
kelly329/lc_all_python
/JZOffer_Python/print.py
1,878
3.875
4
# -*- coding:utf-8 -*- ''' 题目描述: 请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印, 第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。 题目思路: 按之字形顺序打印二叉树需要两个栈我们在打印某一行节点时,拔下一层的子节点保存到相应的栈里如果当前打印 的奇数层,则先保存左子节点再保存右子节点到第一个栈里;如果当前打印的是偶数层,则先保存右子节点再保存左子节点到 第二个栈里。 ''' # class TreeNode: # def __init__(self, x): # self.val = x # self.lef...
c62f6f9b86b46f721e5d6dae473cccc9fb1025f5
kelly329/lc_all_python
/JZOffer_Python/find_path.py
1,292
3.8125
4
# -*- coding:utf-8 -*- ''' 题目描述: 输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。 路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前) ''' # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # 返回二维列表,内部每个列表表示找到的路径 def Find...
e07368da0a188406c397549330450fe8585dae55
kelly329/lc_all_python
/new_all/63-maxInWindows.py
774
3.59375
4
def maxInWindows(nums, size): if not nums or size == 1: return nums res = [] for i in range(len(nums) - size + 1): j = i count = size maxs = nums[i] while count > 0: if nums[j] > maxs: maxs = nums[j] j += 1 count -= 1 res.append(maxs) return res def maxInWindowsQueue(nums, size): if not n...
4873a565ea65e998a4e5ffd6aae5d020ffa80816
kelly329/lc_all_python
/new_all/fullBinaryToSumBinary.py
1,474
3.546875
4
# -*- coding:utf-8 -*- ''' 满二叉树转换为求和二叉树 1.构建二叉树 2.后序遍历二叉树进行求和 3.中序遍历二叉树 ''' class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None self.sum = 0 class Solution: def constructTree(self, pre, tin): if not pre or not tin: return None root = TreeNode(pre[0]) index = tin....
01a6310ad842983bd1b604bd0c59eefb56f07dc6
kelly329/lc_all_python
/new_all/maxThirdPartition.py
838
3.84375
4
def maxThird(nums): nums = sorted(nums, reverse = True) print(nums[2]) ''' 先从右边开始移动再移动左边!!!!! ''' def maxThirdPartition(nums, start, end, k): if start == end: return nums[start] pivot = nums[start] left, right = start, end while left < right: while left < right and nums[right] < pivot: right -= 1 while l...
24c9c884b02c59e33c2b260a3c6fc0f9f8fb162e
kelly329/lc_all_python
/JZOffer_Python/sumS2.py
2,230
4.0625
4
# -*- coding:utf-8 -*- ''' 题目描述: 输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序 例如,输入15,由于1+2+3+4+5 = 4+5+6 = 7+8 = 15,所以打印输出3个连续序列1-5,4-6,7-8。 ''' class Solution: def sumS2(self, tsum): if tsum < 3: return [] small = 1 big = 2 curSum = small + big middle = (1 + ...
1c79f9259859dc593b86f7af9d4917d1ad514c6e
kelly329/lc_all_python
/JZOffer_Python/is_numeric.py
1,546
3.65625
4
# -*- coding:utf-8 -*- class Solution: def __init__(self): self.index = 0 # s字符串 def isNumeric(self, s): if not s or len(s) <= 0: return False flag = self.scanInteger(s) # 如果出现'.',则接下来是数字的小数部分 if self.index < len(s) and s[self.index] == '.': ...
b1935f98bd97ee61e491ccbf37676fb17e30c298
kelly329/lc_all_python
/JZOffer_Python/ReverseList.py
694
3.578125
4
# -*- coding:utf-8 -*- ''' 题目描述: 输入一个链表,反转链表后,输出新链表的表头。 ''' class Solution: ''' 方法:使用三个指针 tmp保存phead的下一个节点,newHead新的头节点,pHead.next指向newHead,再移动一下三个节点即可 https://blog.csdn.net/fuxuemingzhu/article/details/79516154 ''' def ReverseList(self, pHead): if not pHead or not pHead.next: ...
29c0297a9d099e434864345a3d43b2770b6a299a
stackcats/codewars
/4kyu/nim.py
481
3.625
4
def choose_move(game_state): """Chooses a move to play given a game state""" nim_sum = reduce(lambda x,y: x^y, game_state) if nim_sum == 0: for i in range(len(game_state)): if game_state[i] > 0: return (i, game_state[i] - 1) else: for i in range(len(game_state...
68cf2bea1d13ade33b011b415aca76dab05caa7e
matt-opdyke/Ultimate-TicTacToe
/InnerBoard.py
6,745
4.0625
4
import random import numpy as np class InnerBoard(): """This class creates the InnerBoard object. This class implements the InnerBoard object and a few methods for functionality, such as for placing markers and terminal state validation. The larger game board is comprised of nine InnerBoard objects i...
74a6bca2d0348341ec1a392a00042daa57549f48
javierlopeza/IIC2343-2016-2
/Tareas/Tarea 4/python/topological_sorting (adj matrix as 1 list).py
1,675
3.859375
4
def isZeroRow(matrix, r, size): pointer = size * r i = 0 while i < size: if matrix[pointer] == 1: return False pointer += 1 i += 1 return True def clearColumn(matrix, j, size): pointer = j i = 0 while i < size: matrix[pointer] = 0 pointer += size i += 1 return matrix def topological_sort(adjm...
53ab0794ef6caa7df99e4e7ef8f94dc8b60fdc26
Mindp1/TicTacToe
/ticTacToe.py
2,264
3.984375
4
theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ', 'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ', 'low-L': ' ', 'low-M': ' ', 'low-R': ' '} def printBoard(board): print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R']) print('-+-+-') print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mi...
b1b77f83be3aa315d2312224e73b91dccd061dd9
jackw-ai/BlockchainAgentSim
/Agent.py
7,284
3.640625
4
import random import numpy as np from collections import deque from abc import ABC, abstractmethod class Agent(ABC): ''' abstract agent class ''' def __init__(self): super().__init__() # wealth follows a lognormal (right skewed) distribution # self.capital = np.random.lognormal(1, 2) * 10000 #random.rand...
95bdedbc353d1b86f536777b28f8fca63990d8bc
kevindurr/MOOCs
/Georgia Tech - CS1301/Test/6.py
1,693
4.21875
4
#Write a function called are_anagrams. The function should #have two parameters, a pair of strings. The function should #return True if the strings are anagrams of one another, #False if they are not. # #Two strings are considered anagrams if they have only the #same letters, as well as the same count of each letter. F...
baf3cdfaa4e163941c9896dcb399b03a4a2e0793
kevindurr/MOOCs
/Georgia Tech - CS1301/Objects & Algos/Final/8.py
2,728
4
4
names_file = open('babynames.csv', 'r') #----------------------------------------------------------- #The United States Social Security Administration publishes #a list of all documented baby names each year, along with #how often each name was used for boys and for girls. The #list is used to see what names are most c...
622b856988a7621b09fca280ba2564a593df37e1
kevindurr/MOOCs
/Georgia Tech - CS1301/Objects & Algos/Algos_5_2/Problem_Set/5.py
1,403
4.375
4
#Write a function called search_for_string() that takes two #parameters, a list of strings, and a string. This function #should return a list of all the indices at which the #string is found within the list. # #You may assume that you do not need to search inside the #items in the list; for examples: # # search_for_st...
a8cf4a5a1ce8d57396eb875ab3b6d7a675a1409e
kevindurr/MOOCs
/Harvard - CS50/6pset/sentimental/credit/credit.py
819
3.671875
4
from cs50 import get_int cardint = get_int("Number: ") cardstr = str(cardint) cardsum, remainder, i = 0, 0, 0 while cardint > 0: remainder = cardint % 10 cardint //= 10 if i % 2 == 0: cardsum += remainder else: if remainder * 2 >= 10: remainder *= 2 cardsum += r...
eddc52030186ade5fc4dea14645cdb19522df290
chuanzhidong/MachineLearning
/Chapter2/InsertionSort.py
3,385
3.828125
4
__author__ = 'uidw5235' '''Insertion Sort function library''' ''' Chapter 2 ''' # ========================================================== # def isort(args) : plain insertion sort # ========================================================== def isort(xs): n = len(xs) for i in range(1, n): x = xs[i] ...
a7b544425be8d629667975fc19983028bbe51136
Ebi-aftahi/Files_rw
/word_freq.py
735
4.125
4
import csv import sys import os file_name = input(); if not os.path.exists(file_name): # Make sure file exists print('File does not exist!') sys.exit(1) # 1 indicates error items_set = [] with open(file_name, 'r') as csvfile: csv_reader = csv.reader(csvfile, delimiter=','...
692aa5f8afe6bf1f6df7e4475181d20a05879116
wh75er/calc-algorithms
/lab_00/newtonPol.py
2,593
3.78125
4
# Newton polynomial interpolation import os def func(x): return x**3/3 def tableInit(n): x = [] y = [] for i in range(n): x.append(i) y.append(func(i)) return x, y def parsCord(x, y, n, k, order): cls = 0 minim = abs(k - x[0]) for i in range(n): if(abs(k -...
9910837a035db84faa7578becf9bf059d5917b35
Holly-E/pong_game
/pong.py
4,827
3.90625
4
# Implementation of classic arcade game Pong import simplegui import random # initialize globals - pos and vel encode vertical info for paddles WIDTH = 600 HEIGHT = 400 BALL_RADIUS = 12 PAD_WIDTH = 8 PAD_HEIGHT = 80 HALF_PAD_WIDTH = PAD_WIDTH // 2 HALF_PAD_HEIGHT = PAD_HEIGHT // 2 LEFT = False RIGHT = True paddle1_po...
af48f24b1f81ef59890c660dcb21efa0dd09f04f
ccvaille/carom-in-2018
/python/input.py
377
3.515625
4
a = input('输入一个你错过的人:') b = input('输入你最想对ta说的话:') c = input('输入一个时长(比如三分钟):') print('在我年少的时候,遇到了一个人,ta叫' + a) print('可我没有珍惜,如果上天能再给我一次机会,我会对ta说一句话:' + b) print('如果非要给这句话加上一个期限,我希望是 ' + c)
904bca6719dab3f9269d7c1d99c724fa40e2ccd8
mkhoin/2019-winter-keras
/iris.py
2,114
3.53125
4
# Iris Classification with Neural Network # December 23, 2019 # Sung Kyu Lim # Georgia Institute of Technology # limsk@ece.gatech.edu # import packages. import numpy as np import pandas as pd from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.preproces...
469eb1a1596b22bf6423ab324f865dc1d083ade2
mstStudent/campus-map
/CSVandPY/instructor.py
1,477
3.625
4
##Jacob Curtis ##4-23-15 ##Creates the csv that will populate the instructor table for ##the database for MinerMap def getInstructorInfo(): first = raw_input("First name: ") last = raw_input("Last Name: ") dept = raw_input("Department: ") office = raw_input("Office: ") email = raw_input("Email: ")...
7bb3dc041d323337163fab2cf5a19ef6e97c94c2
DharaniMuli/PythonAndDeepLearning
/ICPs/ICP-3/Program1_e.py
1,627
4.21875
4
class Employee: data_counter = 0 total_avg_salary = 0 total_salary = 0 # List is a class so I am creating an object for class mylist = list() def __init__(self, name, family, salary, department): self.empname = name self.empfamily = family self.empsalary = salary ...