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
a3b9e65d74395d4acab9310a446d116d9fabfc4d
iverson52000/DataStructure_Algorithm
/LeetCode/0301. Remove Invalid Parentheses.py
1,117
3.625
4
""" 301. Remove Invalid Parentheses Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results. """ # bfs class Solution: def removeInvalidParentheses(self, s: str) -> List[str]: res = [] q = collections.deque() q.append(s) ...
307fe27ebdd66642a2420c307a1364c2c252352f
iverson52000/DataStructure_Algorithm
/LeetCode/0146. LRU Cache.py
3,283
3.875
4
""" 146. LRU Cache Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. put(key, value) - Set or insert the value if the key...
7cfcc116dda010d0cfdd5bad0318891fa43bbe0c
iverson52000/DataStructure_Algorithm
/LeetCode/0121. Best Time to Buy and Sell Stock.py
670
4
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 3 09:47:11 2019 @author: alberthsu """ """ 121. Best Time to Buy and Sell Stock Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (i.e., buy one a...
09d72e1672433e34f73906903bf7861e0042c85c
iverson52000/DataStructure_Algorithm
/LeetCode/0314. Binary Tree Vertical Order Traversal.py
639
3.703125
4
""" $314. Binary Tree Vertical Order Traversal Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column). If two nodes are in the same row and column, the order should be from left to right. """ # bfs+hashmap import collections res = [] if not root: ...
7f87f658a249feca5d208f33808c858674a2eb45
iverson52000/DataStructure_Algorithm
/LeetCode/0797. All Paths From Source to Target.py
750
3.75
4
""" 797. All Paths From Source to Target Given a directed, acyclic graph of N nodes. Find all possible paths from node 0 to node N-1, and return them in any order. The graph is given as follows: the nodes are 0, 1, ..., graph.length - 1. graph[i] is a list of all nodes j for which the edge (i, j) exists. """ # d...
8f649c228ef521f565fd40a33d25bb2640f74301
iverson52000/DataStructure_Algorithm
/LeetCode/0524. Longest Word in Dictionary through Deleting.py
738
3.78125
4
""" 524. Longest Word in Dictionary through Deleting Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical order. If th...
d53fe4e26b3eb4162a83777cfa72a087ac50eb5b
iverson52000/DataStructure_Algorithm
/LeetCode/0004. Median of Two Sorted Array.py
1,370
3.765625
4
""" !4. Median of Two Sorted Arrays There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may assume nums1 and nums2 cannot be both empty. """ # Binary search class Solution: def findMedianS...
be09b6cbca97dc2d7a2d8ea1344086638e976d7e
iverson52000/DataStructure_Algorithm
/LeetCode/0287. Find the Duplicate Number.py
698
3.984375
4
""" *287. Find the Duplicate Number Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one. """ # binary search class Solution: def findDuplicate(...
9172164f9f8b776514f1bd4a2e7eeb6e5c712211
iverson52000/DataStructure_Algorithm
/LeetCode/0079. Word Search.py
1,213
3.921875
4
""" 79. Word Search Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. """ # dfs class Solution: d...
ac996a74a9189e5d531b53ab8417d18c83a50132
iverson52000/DataStructure_Algorithm
/LeetCode/0111. Minimum Depth of Binary Tree.py
1,427
3.96875
4
""" 111. Minimum Depth of Binary Tree Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Note: A leaf is a node with no children. """ #dfs # Definition for a binary tree node. # class TreeNode(object): # d...
b878f5bfc240cbd64b54766f81a432f4c3ee6615
rickbhardwaj/regex-language
/parser.py
3,496
3.546875
4
class Node(object): def __init__(self): self.regex = None self.prim_value = None self.left = None self.right = None self.child = None def __str__(self): if self.regex == None: return "None" elif self.regex == "prim": return "prim(\"...
d0e40a83f302dc6a0117634b7224494dd69ab992
KuroKousuii/Algorithms
/Prime numbers and prime factorization/Segmented Sieve/Simple sieve.py
832
4.15625
4
# This functions finds all primes smaller than 'limit' # using simple sieve of eratosthenes. def simpleSieve(limit): # Create a boolean array "mark[0..limit-1]" and # initialize all entries of it as true. A value # in mark[p] will finally be false if 'p' is Not # a prime, else true. mark = [True for...
862b61d7ff0c079159910d20570041da0d4747a3
jasimrashid/cs-module-project-hash-tables
/applications/word_count/word_count_one_pass.py
2,043
4.21875
4
def word_count(s): wc = {} # without splitting string beg = 0 c = '' word = '' word_count = {} for i,c in enumerate(s): # if character is end of line, then add the word to the dictionary if i == len(s)-1: #edge case what if there is a space at the end of line or special...
a4b304b43daee02fd18922f855578dd0f8d115d8
Busterz/LPTHW
/Py files/ex34.py
672
3.71875
4
#from sys import argv #script, input_index = argv animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus'] def printAnswers(index): """Print the answers to the list 'animals' in ex34""" #index = input_index if(index == 0): index_name = "1st" elif(index == 1): index_nam...
08f454547bc2210acea622d4901ad931d05d690b
dipesh-lab/python_lang
/src/main/condition.py
217
4.03125
4
x = 200 y = 300 if (x == y): print("Both are equal") if (y >= x): print("Y is greater then X") elif (y== x): print("X and Y are equal") else: print("X is greater then Y") print("End")
468782a501b9384bc3d67e1ec1cfe852ed3378b4
rish29/GeeksForGeeks
/oracle/palindrome/solution.py
484
3.75
4
#code test_cases = int(input()) while test_cases: temporary_no = 0 palindromic_number = int(input()) validate_palindromic_number = palindromic_number while validate_palindromic_number: rem = validate_palindromic_number % 10 temporary_no = temporary_no * 10 + rem validate_palindro...
bfa9b0f63a8843190450c6daf6baf933a858bd66
virtualvector/competitive-coding
/codechef/feedback.py
161
3.90625
4
test = int(raw_input()) for _ in range(test): string = raw_input() if(string.find("010")>=0 or string.find("101")>=0):print "Good" else: print "Bad"
df599956f33b0f358ba6807db60bb00f0814d2d3
burekwithkajmak/Labb-LeoG-Te19c
/labb2-e.py
2,213
3.765625
4
#En variabel som används för att spara datan från input som användaren matar in. startintervall = int(input("Startintervall: ")) #En variabel som används för att spara datan från input som användaren matar in. slutintervall = int(input("Sluttintervall: ")) #En variabel som används för att spara datan från input s...
762957c898f6d701c91670e75b268b0a135afa7d
Horsefactor/mood_face_AI
/HeadWatcher.py
4,234
3.71875
4
from abc import ABC, abstractmethod from typing import List import Head class HeadWatcher(ABC): """ The Subject interface declares a set of methods for managing subscribers. """ @abstractmethod def attach(self, head: Head) -> None: """ Attach an observer to the subject. """...
f5812e58373f52e38f8efa72d8e4a6627526f194
prateek951/AI-Workshop-DTU-2K18
/Session1/demo.py
1,816
4.75
5
# @desc Working with Numpy import numpy as np # Creating the array using numpy myarray = np.array([12,2,2,2,2,2]) print(myarray) # The type of the array is np.ndarray whereas in python it would be list class print(type(myarray)) # To print the order of the matrix print(myarray.ndim) # To print the shape of the a...
58558f014aa28b29b9e2ad662cd783ff524bd220
prateek951/AI-Workshop-DTU-2K18
/Session-5 Working on Various Python Library/numpyops.py
2,447
4.375
4
my_list = [1,2,3] # Importing the numpy library import numpy as np arr = np.array(my_list) arr # Working with matrices my_matrix = [[1,2,3],[4,5,6],[7,8,9]] np.array(my_matrix) # Create an array np.arange(0,10) # Create an array keeping the step size as 2 np.arange(0,10,2) # Arrays of zeros np.zeros(3) # Array ...
c51d25e54730bb403e0f633546d3347feefbad84
D4UR191/ICCO_Estructurada
/Act8.py
271
3.734375
4
# Comparación de cadenas nombre = [] intentos = 1 print("\nTest Dragon Ball") while nombre != 'GINE': print(f"\nIntento: {intentos}", end="") nombre = input("Cual es el nombre de la madre de Goku? ").upper() intentos += 1 print("\nCorrecto!")
e5ba379d2bd6419291160ff8d77d2791626e1458
D4UR191/ICCO_Estructurada
/Act2.py
151
4.0625
4
# Invertir una cadena de caracteres cadena = (input("Ingrese la cadena a invertir: ")) invertida = cadena[::-1] print("\nInvertida:", invertida)
7cf79542567ee29752ad8606776f45e1f1b32501
abhiis/python-learning
/basics/modules.py
112
3.515625
4
from utils import find_max numbers = [1, 2, 5, 7, 8, 6, 9, 1, 2, 6, 8, 25, 8] max = find_max(numbers) print(max)
10909526062c5f6942d088d73b2d9615096dd2de
abhiis/python-learning
/basics/Dictionary.py
414
3.859375
4
#just like JS objects, having key value pairs #patient = { # "name": "John", # "age": 28, # "new": True # } numberInWords = { "0": "Zero", "1": "One", "2": "Two", "3": "Three", "4": "Four", "5": "Five", "6": "Six", "7": "Seven", "8": "Eight", "9": "Nine", } output = '' number = i...
e4db9a855ebaf188c4190ec4c564a0c46a3c573f
abhiis/python-learning
/basics/carGame.py
889
4.15625
4
command = "" is_started = False is_stopped = False help = ''' start: To start the car stop: To stop the car quit: To exit game ''' print("Welcome to Car Game") print("Type help to read instructions\n") while True: #command != "quit": if we write this condition, last else block always gets executed command = inpu...
7ff14386c1cbd0fd4b510479be76cc80f8f5c705
juraj80/python-weekend-ba-task-master
/example/solution.py
2,928
3.734375
4
import csv import sys import datetime #bags = 1 data_file = './example/example.csv' ticket_origin = 'WIW' ticket_destination = 'RFS' route = [] """Helper function for converting datetime string to the datetime object.""" def parseToDate(dateString): return datetime.datetime.strptime(dateString, "%Y-%m-%dT%H:%M...
a025feffdd197313ece31237a2eeb92ad63f7dfe
pumatus/wlpcpy
/returnmanyvalue.py
200
3.59375
4
import math def move(x, y, step, angle=0): nx = x + step * math.cos(angle) ny = y - step * math.sin(angle) return nx, ny, angle print('%s, %s, %s' % (move(100, 100, 60, math.pi / 6)))
7af98b62d77b8f746a25af5e1858946a789e4690
redashu/swrm
/datasc.py
313
4.09375
4
import matplotlib.pyplot as plt x=[5,3,9] y=[12,15,10] plt.xlabel('distance') plt.ylabel('time') plt.grid(c='green') plt.scatter(x,y,label="stations") # this will plot a line plt.plot(x,y,label="railway track") plt.bar(x,y) plt.legend() # it will display label in plots plt.show() # to show the graph
3a2efab9c9b24e1400e3ab24389860f2eebb42d1
MOHAMMADHOSSEIN-JAFARI/Python-exercises
/Small Letters Capital Letters.py
154
3.65625
4
a = input() b = sum(1 for c in a if c.isupper()) e = sum(1 for d in a if d.islower()) if b > e: print(a.upper()) else: print(a.lower())
29ea010ec892e7f9b49342eb34b855ea9f090726
kavindu23110/Tk_UserInterface
/Round_button.py
2,184
3.5
4
#######Basic switch in tkinter###### from tkinter import * root= Tk() class CustomButton(Canvas): def __init__(self, parent, width, height, color, channelNo, txt="", command=None): Canvas.__init__(self, parent, borderwidth=1, relief="flat", highlightthickness=0) self.command = command...
b7fed999d65a409627d143ae7f0a9e8e2086dfc8
denamyte/Hyperskill_Python_07_Currency_Converter
/Currency Converter/task/previous/cconverter4.py
264
3.8125
4
currencies = {'RUB': 2.98, 'ARS': 0.82, 'HNL': 0.17, 'AUD': 1.9622, 'MAD': 0.208} coni_sum = float(input()) for curr, rate in currencies.items(): value = round(rate * coni_sum, 2) print(f'I will get {value} {curr} from the sale of {coni_sum} conicoins.')
c69077d4872fa21cddbf88b09cab2faf4c7010be
ryanZiegenfus/algorithms_practice
/codewars/challenges.py
2,239
4.125
4
##################################################################################################### # 1 # Create fibonacci sequence with n elements and ouptut it in a list. If n == 0 return empty list. # 0 1 1 2 3 5 8 11 19 ...etc # [0, 1, 1, 2, 3, 5,] def fib_sequence(n): base = [0, 1] if n == 0: r...
7ce5497b476b0a5f144f5d99a4e073f8cb7d4dde
mustardgnome/Egglang
/ast.py
1,338
3.53125
4
import bytecode import objects """ This is our abstract syntax tree. Our program will be represented by this when it is parsed """ class Node(object): def __eq__(self, other): return (self.__class__ == other.__class__ and self.__dict__ == other.__dict__) def __ne__(self, other): ...
908b17df202df3f3aa0e91c8ed4a036592c64d21
BSteposz/Unittest
/class test/test_survey.py
905
3.890625
4
import unittest from survey import AnonymousSurvey class TestAnonymousSurvey(unittest.TestCase): """ Test for AnonymousSurvey class """ def setUp(self): question = "Favourite book" self.my_survey = AnonymousSurvey(question) self.responses = ['Słownik języka polskiego', 'recepty', 'Manu...
73190cea5b0d08cd2a4ec7b0416e895541fbc7da
smullinmatteo/One-Month-Coursework
/Python Coursework/lists.py
428
3.671875
4
the_count = [1, 2, 3, 4, 6] stocks = ["AAPL", "GOOG", "TSLA"] random_things = ["Puppies", 55, "Anthony Weiner", 1/2, ["Oh no", "A list inside a list"]] # we can also build lists, first let's start with an empty one people = [] people.append("Mattan") people.append("Sarah") people.append("Chris") # now we can print t...
5bc889e9c31938876a4f7be8f176a6f8cbb0cc98
yehuohan/ln-misc
/code/automatic-differentitation/adpy_test.py
600
3.84375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import adpy as ap def sigmoid(x): return ap.divide( ap.Constant(1), ap.add( ap.Constant(1), ap.exp(ap.substract(ap.Constant(0), x))) ) def sigmoid_(x): return ap.Constant(1) / (ap.Constant(1) + ...
43ef001cac11bbb58fd20123e232edff7b69cbb8
pavanimallem/mallempavani
/guvi53s.py
78
3.5
4
n=int(input()) sum=0 while(n>0): dig=n%10 sum=sum+dig n//=10 print(sum)
70c61a3d8eddb579c6f66fc9e4ff57b71ee8df9d
TJZ1990/leetcode
/Python/110-Balanced Binary Tree-V1.py
679
3.765625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Soluion(object): def isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ return self....
c2ee5c57990661c170bbddc29773bbf5ced76a5d
TJZ1990/leetcode
/Python/102-Binary Tree Level Order Traversal-V1.py
795
3.796875
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ ...
e4aa0a6288f816e948e9764c3680677c9bd9e968
TJZ1990/leetcode
/Python/56-Merge Intervals.py
713
3.921875
4
#First sort the intervals by its start. #If two intervals overlap, join them. # Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution(object): def merge(self, intervals): """ :type intervals: List[In...
2f6e9210d2d944f3d126f5004a92078871a86142
cvlasov/sqrt-law
/scripts/actor3_preprocessing.py
1,995
3.5
4
""" This script finds all JPEGs with specific dimensions in a directory, converts them to grayscale, rotates the portrait ones to landscape, and puts all the resulting JPEGs into another directory. """ import argparse import subprocess import time parser = argparse.ArgumentParser() parser.add_argument("-fr", "--from-...
3a8cabb19661d8ce5a24a10a7a7a7621197adffd
Rombur/utils
/python/eigenvalues.py
715
3.703125
4
#! /usr/bin/env python #----------------------------------------------------------------------------# # Python code # Author: Bruno Turcksin # Date: 2011-11-08 18:05:24.776750 #----------------------------------------------------------------------------# import numpy as np import scipy.linalg import pylab filename = ...
ce2cf069615f1fa48ccbb8acf95c604e795b7e7d
shariqfarhan/Explore
/Assignment_5/model.py
6,493
3.515625
4
# We change the way we define the neural network. Earlier we used to work one convolution layer at a time, now we'll add more operations on top of the convolution layer # All of this will fall under 1 block. dropout_value = 0.1 class Net(nn.Module): def __init__(self, use_ln: bool = False, use_BN: bool = True...
24b5ac03c349965fe696beecd6500ab08caaa93e
Jmueller87/learningpython
/quadratic formula (first program).py
509
3.953125
4
# This was my first program. a = float(input("Enter the coefficient of the second degree variable:")) b = float(input("Enter the coefficient of the first degree variable:")) c = float(input("Enter the constant:")) root =((b**2)-4*a*c) if root < 0: print("Domain Error") else: d = root**0.5 ...
0b1b0635a290786f00144bef89137b12549089fe
gitly110/python_exc
/python从入门到实践/class9/admin.py
500
3.53125
4
from class9.user import User class Admin(User): def __init__(self, first_name, last_name): super().__init__(first_name, last_name) self.privileges = Privileges() class Privileges(): def __init__(self): self.privileges = ["can add post", "can delete post", "can ban user"] def sh...
357cb422cdf28e12bb34d6922b7c74626cf457b5
gitly110/python_exc
/untitled1/part2/diguichazhao.py
489
3.8125
4
#二分查找,递归法 def mid_search(source,n): source.sort() mid=len(source)//2 if len(source)>=1: print(source) if n>source[mid]: mid_search(source[mid+1:],n) print(source.index(n)) elif n<source[mid]: mid_search(source[:mid],n) print(source.inde...
bd6ddd716355fb1e1529a58faec0a6cd9cce3d40
gitly110/python_exc
/python从入门到实践/file10/store_file.py
960
3.875
4
import json def store_num(): num = input('Please enter your favour number:\n') file = 'favour_num.txt' with open(file, 'w', encoding='utf8') as fw: json.dump(num, fw) return num def get_num(): file = 'favour_num.txt' try: with open(file, encoding='utf8') as f: num...
37ec44a4c625be4aff3bcb25f88822f9a13d5d87
l200183203/praktikum-algopro
/ainayah syifa prac 11 act 2.py
1,371
4.21875
4
#Practic 11. Activity 2. Make Simple Calculator. by@Ainayah Syifa Hendri from Tkinter import Tk, Label, Entry, Button, StringVar my_app = Tk(className= "Simple calculator") L1 = Label(my_app, text= "Number 1") L1.grid(row=0, column=0) str1 = StringVar() E1 = Entry(my_app, textvariable= str1) E1.grid(row=0, c...
b092c9359ba7df8ae4f09893472d772b6c219783
marronjo/teaching-python
/week4.py
210
4.09375
4
#practice nesting for loops #printing out 10x10 multiplication tables for number1 in range(1,11): for number2 in range(1,11): print(number1*number2,end="\t") print("\n") number = 4 second = 5
3ad5a2b3f7fad063430ebd080615befa344ce52d
morteneiby/exam
/task1.py
2,057
3.5
4
# String 'Hello' eller "Hello" "Det er John's bil" 'John sagde: "Hej"' # int = heltal - float = kommatal # bool = komplet system til logiske operationer, udtrykkes som sandt eller falsk. listA = [1, 2, 'A', 'B', 1, 2, 'A', 'B'] # Ordnet, kan ændres, duplikerede værdier print(listA[0]) print(listA[-1]) print(listA[2:5]...
409e94361c99c3833dcc7990a2593b3ee5b10f10
amolgadge663/LetsUpgradePythonBasics
/Day7/D7Q1.py
393
4.1875
4
# #Question 1 : #Use the dictionary, #port1 = {21: "FTP", 22:"SSH", 23: "telnet", 80: "http"}, #and make a new dictionary in which keys become values and values become keys, # as shown: Port2 = {“FTP":21, "SSH":22, “telnet":23,"http": 80} # port1 = {21: "FTP", 22:"SSH", 23: "telnet", 80: "http"} print(port1)...
517f5396a3e74f8f4c1f727a3224f21dc22be127
amolgadge663/LetsUpgradePythonBasics
/Day4/D4Q2.py
212
4.40625
4
# #Question 2 : #Explain using #islower() #isupper() #with different kinds of strings. # st1 = "I am Amol." print(st1) print("String isLower? ", st1.islower()) print("String isUpper? ", st1.isupper())
9082ddffa4d7ce5157dae72066d2cb108ef0d744
YourStyle/HSE_DSBA_20_WS8_LISTS
/5.py
239
3.71875
4
string = input().split() lists = [[]] for i in range(len(string)): orig = lists[:] new_list = string[i] for j in range(len(lists)): lists[j] = lists[j] + [new_list] lists = orig + lists print(lists)
5e2b165a136b758605450d017f19ec55599febaa
HoodyH/Pavlov-Old
/core/src/message_reader.py
3,177
3.84375
4
def find(to_find, find_in, starting_point=None): if to_find == "": return sample_array = to_find.upper().split() sentence_array = find_in.upper().split() if starting_point is None: # This loop look for that keyword il all the sentence for i in range(0, len(sentence_array)): ...
a2c55fb15ae28311250159da420d67bb7092c113
Ailol/Simple-FTP-server
/server.py
1,025
3.640625
4
import argparse import os from network.sftp import Sftp class Server(object): """ Simple server implementation SFTP holds all the magic Starts the server up by arguments given by the user. """ def __init__(self, *args): try: self.sftp = Sftp(args[0], args[1]...
beda4145626fb9240a191f15603f222c28c1e475
a-mcloughlin/final-year-project
/internal/political_leaning/analyse_political_leaning.py
1,676
3.53125
4
from internal.political_leaning.political_leaning_ml import retrieve_ml_model,predict_from_model import internal.word_processing.interpret_data as interpret_data # From a set of tweets and a country code, predict the political leaning of the set of tweets # Classify each tweet with a political leaning, and get...
a13c87f4e2bdf13806bb9b8f740c62c7c69e6147
wjwjwj2223/NeteaseAlgorithm
/1/1_6_1.py
447
3.828125
4
def check(list): man_list = [] for item in list: if item == 'f': man_list.append(item) elif item == 'm': if len(man_list) == 0: return False man_list.pop() else: return False if len(man_list) == 0: return True ...
87a4793a0c3e363465d5b3d007d93c6127d6bf0d
wjwjwj2223/NeteaseAlgorithm
/6/6_0_0.py
1,142
3.640625
4
class Student(object): def __init__(self, name, age, score): self.name = name self.age = age self.score = score def __lt__(self, sdt): if self.score == sdt.score: if self.name == sdt.name: return self.age < sdt.age else: r...
da8cc0b278f2871cf89b916c4e5e654e9adcf4b5
wjwjwj2223/NeteaseAlgorithm
/5/stand_2_0.py
710
3.859375
4
class BST(object): def __init__(self, key): self.left = None self.right = None self.label = key def bst_add(tree, x): if tree is None: return BST(x) if x < tree.label: tree.left = bst_add(tree.left, x) elif x > tree.label: tree.right = bst_add(tree.righ...
8fa01baf63addeb032fa39180dd2bc35b7a5a31b
wjwjwj2223/NeteaseAlgorithm
/2/1_8_2.py
476
3.53125
4
def move(x, y): if x == n - 1 and y == n - 1: return 1 else: count = 0 if x + 1 < n: if city_map[x + 1][y] == 0: count += move(x + 1, y) if y + 1 < n: if city_map[x][y + 1] == 0: count += move(x, y + 1) return count...
a094ae1fa7edfaded9302e6205ae0e48b9de3ed5
DiegoPacheco2/scripts_python
/primeiro.py
123
3.609375
4
nome=input('Qual e o seu nome: ') idade=input('Qual e sua idade: ') peso=input('Qual e seu peso: ') print(nome,idade,peso)
26fe7a615586306a204995cbffbf3b0f5225561a
DiegoPacheco2/scripts_python
/desafio3.py
121
3.6875
4
nu1=input('Primeiro número: ') nu2=input('segundo número: ') soma=int(nu1)+int(nu2) print('A soma é {}'.format(soma))
9dd331a0e303c08d4ab734373299e7573a758082
tarandeept/webreg-api
/webreg_api/scraper.py
5,598
3.578125
4
""" This module is the main scraper module It needs the year, quarter, and filepath of the file it scrapes It extracts course information from the file and stores it in DB """ HEADERS = ['code', 'type', 'sec', 'units', 'instructor', 'time', 'place', 'final', 'max', 'enr', 'wl', 'req', 'nor', 'rstr', 'textb...
b9137a4e35a25daefade7a3a063699e02ebebd01
KIMDOKYOUNG/HL_Contributhon
/03_DeBug/average.py
206
3.625
4
def average(nums): sum = 0 n = 0 for n in nums: sum += x n += 1 avg = sum / n print(avg) # 평균값은 22.857142857142858 이여야 함. average([2, 4, 6, 8, 20, 50, 70])
eedf2c2201878ea6cd3b38978cb751930962d99f
nullbite-coder/Python-Beg-Projects
/ROCK_Paper_Sicsors Game.py
1,356
3.984375
4
import random def comp_choose(): elem = ['r','p','s'] comp = random.choice(elem) return comp def winner_check(comp,user): if(comp.lower() == user.lower()): print("Tie") return if(comp.lower() =='r' and user.lower() == 's'): print("Computer Won") return ...
913c3ad8d458266c9018050972560d612cdde81a
jarinaktermou5/Python-project
/python.py
2,292
3.71875
4
from tkinter import * class CurrencyConverter: def __init__(self): window = Tk() window.title("Currency Converter") window.configure(bg="yellow") Label(window, font="Helvetica 12 bold", bg="yellow", text="Amount to convert").grid(row=1, column=1, ...
20d854cb30bbe62d11f47565e0e0baf4787fdb4f
VOliMartins/CalcNum
/newtonnl2_inp.py
2,296
3.609375
4
''' Newton para sistemas não lineares Diversos chutes iniciais Saída por documento excel ''' def method(): import numpy as np from mpmath import * from sympy import * from sympy import var from sympy import sympify from sympy import lambdify from xlwt import Workbook ...
e15556e403f6554f792a1217c0505b30856bea1a
yunhsiang0308/Python200805
/day3-5.py
595
3.84375
4
while True: print('------------------------------') print('1.加法') print('2.減法') print('3.乘法') print('4.除法') print('5.離開') x=int(input('請輸入選項:')) if x==5: print('Bye~~') break a=int(input('請輸入第一個數:')) b=int(input('請輸入第二個數:')) if x==1: ...
0687b63bca282335c7fb062eeecc709b306c57e9
littlewhitelion/Phi-Generator
/phi generator.py
271
3.9375
4
#This program is to prompt the user to ask how many decimals places they want the number phi displayed to import math from decimal import * def phi(): user1 = input("Desired phi length: ") getcontext().prec = user1 phi1 = (1 + Decimal(5).sqrt())/2 print phi1 phi()
59125fe5d98160896e811a9be0cf6421a73e711c
DRCurado/Solids_properties
/Circle.py
744
4.21875
4
#Circle shape #Calculate the CG of a circle. import math #insert the inuts of your shape: unit = "mm" #insert the dimensions of your shape: diameter = 100; #Software do the calculations Area = math.pi*(diameter/2)**2; Cgx = diameter/2; Cgy = diameter/2; Ix= (math.pi*diameter**4)/64; Iy= (math.pi...
9f3bae4532bba8df5a35cdb4b04f6f448e0e9cd2
chakra0501/addressBook
/AnalysisOperations.py
1,866
3.578125
4
import numpy as np from SkipListOperations import SkipListOperations #This file collects data for the number of operations #for our Skip List implementation. # #1. This program writes the number of operations taken #by the insert() function to insertData.txt. # #2. This program writes the number of operations taken #b...
84daaa4aece6a49d9c000988dad85674aa5571b7
Red-Fox-Lab/simple-program
/numbers program.py
441
3.796875
4
#You enter the number #The program shows you the collection of simple numbers you can divide your number with while True: v = int(input("Write number: ")) t = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101] natural = range(1, 1000000) for n in t: ...
d5a0d6d0e81ccf85067d7ae65a148efe962d22d8
lovesly/pythonPG
/bilibili/PyForEverybody/chp3/p12.py
286
3.859375
4
x = 10 if x < 2 : print('small') elif x < 10 : print('medium') else : print('large') print('All done') # try catch astr = "Hello Bob" try: istr = int(astr) except: istr = -1 print('First', istr) astr = '123' try: istr = int(astr) except: istr = -1 print('Second', istr)
08a805c737888e44ff1fb2f88669b968ef6e3735
lovesly/pythonPG
/bilibili/PyForEverybody/chp4/p17.py
376
3.84375
4
def computePay(hours, rate): print("In computePay", hours, rate) if (hours > 40): pay = rate * 40 + rate * 1.5 * (hours - 40) else: pay = hours * rate return pay xh = input("Enter Hours: ") xr = input("Enter Rate: ") try: fh = float(xh) fr = float(xr) except: print("Error, please enter numeric in...
315bbed9d2f8a8a869bf02eebb6a2caf2e4edd29
juliosol/CS_61a
/exp.py
4,197
4
4
class Link: """A linked list. >>> s = Link(1) >>> s.first 1 >>> s.rest is Link.empty True >>> s = Link(2, Link(3, Link(4))) >>> s.second 3 >>> s.first = 5 >>> s.second = 6 >>> s.rest.rest = Link.empty >>> s # Displays the contents o...
5d19ba7e0831aa11d503f087a6055410339f9918
verdantran/ud120-projects
/svm/svm_author_id.py
1,556
3.546875
4
#!/usr/bin/python """ This is the code to accompany the Lesson 2 (SVM) mini-project. Use a SVM to identify emails from the Enron corpus by their authors: Sara has label 0 Chris has label 1 """ import sys from time import time sys.path.append("../tools/") from email_preprocess import preprocess ### ...
46c5268ff9a97603abefad2d44a7c74f6cf6598a
zoeydao/yendao-labs-c4e22
/Lab3/homework/serious11.py
252
3.8125
4
def is_inside(l1,l2): x1 = l1[0] y1 = l1[1] x2 = l2[0] y2 = l2[1] x2w = l2[0] + l2[2] y2h = l2[1] + l2[3] if (x2 <= x1 <= x2w) and (y2 <= y1 <= y2h): inside = True else: inside = False return (inside)
1152fe92068275fa7389c68ed4fc940ed13bf915
kynan/CodeDojo30
/fib.py
939
3.765625
4
class Fibonacci(object): _cache = {0: 1, 1: 2} def __init__(self, n): self.n = n def get(self, n): if not n in Fibonacci._cache: Fibonacci._cache[n] = self.get(n-1) + self.get(n-2) return Fibonacci._cache[n] def next(self): return Fibonacci(self.n + 1) ...
295dc3cba69c6420174aaa47e8235400fa043514
941design/dojo
/codewars/python/tic_tac_toe.py
1,030
4
4
def is_solved(board): ''' https://www.codewars.com/kata/525caa5c1bf619d28c000335/python ::start:learnings:: Flattening the board beforehand makes it easier to index the fields as well as to describe winning patterns. This can be generalized, such that simplification may be appropriate, ...
93bd558a5dc7ad09a1c8171fa0ae8764d529e393
941design/dojo
/codewars/python/iq_test.py
779
3.796875
4
import doctest def iq_test(s): """ >>> iq_test('1 1 2') 3 >>> iq_test('2 1 3 5') 1 >>> iq_test('1 2 3 5') 2 >>> iq_test('1 3 5 2') 4 >>> iq_test('2 2 1') 3 >>> iq_test('1 2 4 6') 1 >>> iq_test('2 1 4 6') 2 >>> iq_test('2 4 6 1') 4 """ numbers...
8f7a163218aa767c258885178522d7140d02f51e
941design/dojo
/rosalind/python/src/fibd.py
264
3.578125
4
import numpy as np def fibd(n, m): ''' https://rosalind.info/problems/fibd/ >>> fibd(6, 3) 4 ''' if m < 1: raise ValueError pop = (m-1) * [0] + [1] for _ in range(n-1): pop = pop[1:] + [sum(pop[:-1])] return sum(pop)
d1f9be10a2466a775babba9a42d09aef768d2786
Hilix/bootcamp
/arrays.py
127
3.65625
4
cars = ["Ford", "volvo", "BMW", "Range Rover"] cars.remove("volvo") cars.pop(2) cars.append("Toyota") cars.sort() print(cars)
448ddae1eb243d31b32d1955c0e6c8104fafb400
Akshay9597/codechef
/pins.py
183
3.609375
4
t = int(input()) for i in range(t): n = int(input()) """ total = 9 * (10**(n-1)) # print(total) same = 9 * (10**(int((n-1)/2))) print(same,total) """ print("1",10**(int(n/2)))
45e20efd919cb4ab2fc2b6b03449a8066b8f4f2a
alphaolomi/cryptography-algorithms
/transposition_encryption.py
1,122
4.1875
4
# Transposition Cipher Encryption def main(): my_message = 'Common sense is not so common.' my_key = 8 cipher_text = encrypt_message(my_key, my_message) # Print the encrypted string in cipher_text to the screen, with # a | (called "pipe" character) after it in case there are spaces at # the en...
1c30dd68582708f430984f466a4029bb9a84264e
rragundez/utility-functions
/ufuncs/dictionaries.py
2,369
3.796875
4
def get_values_from_key(a_dict, *, key, recursive=True, only_dict=False): """Lookup key in multi-level dictionary. This function will transverse a multi-level dictionary and extract to a list all the values corresponding to key `key`. `max_level` argument indicates how deep to look in the dictionary. ...
ca827f71d84324d576adac8192f0391af29a457c
rragundez/utility-functions
/ufuncs/random.py
699
4.1875
4
def generate_random_string(length, *, start_with=None, chars=string.ascii_lowercase + string.digits): """Generate random string of numbers and lowercase letters. Args: length (int): Number of characters to be generated randomly. start_with (str): Optional string to s...
0c0a181e57d681727fa325fa3a14e54a9767a351
rragundez/utility-functions
/ufuncs/xml.py
3,192
3.640625
4
from lxml import etree from lxml.builder import ElementMaker import pandas as pd def xml_to_dict(xml_tree): """Convert xml information into a dictionary. Get XML tags and text as keys and values in a dictionary. If the tag repeats the different texts/values will be concatenated using a smicolon (;)....
7e682d984b99de7e5ae4f53eebfb7cdd21b2ba99
priyankavanaja/casestudy
/random.py
325
3.703125
4
# Import numpy as np import numpy as np # Set the seed np.random.seed(123) # Generate and print random float print(np.random.rand()) # Import numpy and set seed import numpy as np np.random.seed(123) # Use randint() to simulate a dice print(np.random.randint(1,7)) # Use randint() again print(np.random.randint(1,7...
50cc054b1ba7dd2c7e72ccd3e1f08395842f32e7
Crhistianz/pchqtcRetoS3
/ejercicios3.py
149
3.8125
4
numero = int(input("Ingrese un número: ")) lista = [] i=1 while i<=10: valor = numero*i lista.append(valor) i+=1 else: print(lista)
959cf3c50cba753780a737e87983a176d2613f7e
ryukinix/ai-ufc
/src/python/multiple_linear_regression.py
2,021
3.5
4
#!/usr/bin/env python # coding: utf-8 """Regressão Múltipla Notas ----- Dataset: uma função linear com um ruído gaussiano de media 0 e variancia não-unitária. N = σ * randn(n) + μ y(X) = X * beta + e ŷ(X) = X * beta Legenda: + N uma variável aleatória normal. + σ é a variância + μ é a média + n é a quantidade...
bed22c39c992bab87d3f82cd7dcfc112fb380400
Skycrab/code
/Java/language_imple_pattern_source/stream/csv/cmt.py
286
3.546875
4
import sys for line in sys.stdin: # for each line from stdin if line.startswith('#'): continue # ignore comment lines values = line.strip().split(',') # break into columns values = map(str.strip, values) # strip whitespace around elements print values
417cd034007f9ac8241fac4be51c5f5fd880b286
paulremerata/exam
/first code.py
848
3.71875
4
random_numbers = [76,23,1,45,7,5,2,1,2,2,2,4,88,66,66,55,5,12,314,545,777,12,32] def remove_duplicates(x): l=[] c=True for i in x: for j in l: if i==j: c=False if c: l.append(i) c=True return l print "Sorted and Purified "+str(sorted(remove...
931420d3621bd7098f811356bc63ad8051f4aa7c
tuess/python
/骰子动画/button.py
995
3.703125
4
#!/usr/bin/python # -*- coding: utf-8 -*- from graphics import * class Button: def __init__(self,win,center,width,height,label): w,h=width/2.0,height/2.0 x,y=center.getX(),center.getY() self.xmin,self.xmax=x-w,x+w self.ymin,self.ymax=y-h,y+h p1=Point(self.xmin,self.ymin) ...
91a19b5ee8c2569dc9aff672aab086631d669897
tuess/python
/课设/test.py
7,423
3.65625
4
#!/usr/bin/env python #-*- coding:utf-8 -*- import os def show(): infile=open("student.txt","r") while True: a=infile.readline() if a!="": b=a.split()#拆分 else: break #格式化插入 print("姓名:",b[0]+'\t'+"语文:",b[1]+'\t'+"数学:",b[2]+'\t') print('\n') inf...
c10cb232f6c7b665dbf7fe0b672a8034dd97b6af
lukeitty/problemset0
/ps0.py
2,630
4.25
4
#Author: Luke Ittycheria #Date: 3/28/16 #Program: Problem Set 0 Functions #Function 0 def is_even(number): '''Returns a value if the number is even or odd''' if number == 0: return True if number % 2 == 0: return True else: return False return evenOrOdd #############################################...
e79db59ede0b848604a85f6b042c29773cdbe148
mdelia17/bigdata-labs
/averagewordlength/mapper.py
228
3.671875
4
#!/usr/bin/env python3 """mapper.py""" import sys for line in sys.stdin: line = line.strip() words = line.split("") for word in words: letter = word[0].lower() print("%s\t%i" % (letter, len(word)))
5be8650b70b9d37f55dd59728d7e040d92d53f89
xaoqian/homework
/pack_1/задача1_3.py
233
3.9375
4
a = int(input('a: ')) if a == '0': print('error') elif a =='1' : print(' yes ') else: for i in range(2,a) : if a % i == 0: break elif a % i != 0: print('yes!')
39b91946afdb07d27c8314405268e89e842c8840
benichka/PythonWork
/favorite_languages.py
707
4.40625
4
favorite_languages = { 'Sara' : 'C', 'Jen' : 'Python', 'Ben' : 'C#', 'Jean-Claude' : 'Ruby', 'Jean-Louis' : 'C#', } for name, language in favorite_languages.items(): print(name + "'s favorite language is " + language + ".") # Only for the keys: print() for k in favo...
f52a6d2bb9c128e7d731f977ab8f7dc37466dd17
benichka/PythonWork
/user.py
221
3.53125
4
user_0 = { 'username' : 'massonbedeaub', 'first' : 'Benoit', 'last' : 'Masson-Bedeau' } for key, value in user_0.items(): print() print(key + ": key") print(value + ": value")