blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
e4a4fc0bce98a51daea0794b51466a9477b6569b
AlbertGithubHome/Bella
/python/image_operation/image_test.py
190
3.546875
4
# image thumbnail from PIL import Image im = Image.open('test.jpg') w,h = im.size print('Original image size: %s:%s' % (w, h)) im.thumbnail((w//2, h//2)) im.save('thumbanil.jpg', 'jpeg')
fe384babe2de6c8b8caa1b699a97fcfd93f5d843
AlbertGithubHome/Bella
/python/meeting/meeting.py
573
3.78125
4
#每一行数据代表一条会议申请 #(会议编号,开始时间,结束时间) MeetingList = [ (1,13,15), (2,11,13), (3,20,22), (4,16,19), (5,11,16), (6,8,14), (7,14,18), (8,9,12), (9,16,20), (10,13,17) ] def meeting_cmp(data): return data[2] MeetingList = sorted(MeetingList, key=meeting_cmp) #for x in MeetingList: # print(x) #以下是输出结果,按结束时间排序的 ...
62e637a5b6e7a7546ed3c0fae826ad7b2eb7ce12
AlbertGithubHome/Bella
/python/data_type.py
284
3.796875
4
print("this is string") print(123) print(0.000012) print(False) print(5 > 3) print(None) # this is annotation format print("10 / 3 =", 10 / 3) print("10 // 3=", 10 // 3) # output result ''' this is string 123 1.2e-05 False True None 10 / 3 = 3.3333333333333335 10 // 3= 3 '''
02287ad64392cd38f43454ac9e90dbad9e08bf76
AlbertGithubHome/Bella
/python/file_operation/find_conflict.py
850
3.546875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # find confict L = [] with open('1.txt', 'r') as file: content = file.readline() content = file.readline() while content: print(content[0:-1].split('\t')) L.append(content[0:-1].split('\t')) content = file.readline() for x in range(len...
238ed03d076b3e75d14d94c9e8f5f9cb9e3d7b6b
yabedin/dcapp
/preprocessing/convert_to_csv.py
1,674
3.65625
4
import json import csv def convert_to_csv(received_data, filename): ''' DESCRIPTION ------------- Writes a JSON file from IBM Watson STT API to a CSV file saved to the root directory, with headers: WORD, SPEAKER, FROM, TO. WORD = specific word spoken SPEAKER = speaker label FROM = timest...
bb563aa201ed168ef241f723d501c13f146bb3b9
wenzlern/ma
/python/Uoft_plot/PlotClass.py
2,319
3.8125
4
#!/usr/bin/env python """Plotting functions This class provides objects and methods to simplify plotting""" __author__ = "Nils Wenzler" __copyright__ = "Nils Wenzler" __version__ = '1' __maintainer__ = "Nils Wenzler" __email__ = "wenzlern@ethz.ch" #imports import matplotlib.pyplot as plt from numpy impo...
4740f88aedeb28db6bfb615af36dfed7d76fda0f
vincent-kangzhou/LeetCode-Python
/380. Insert Delete GetRandom O(1).py
1,434
4.1875
4
import random class RandomizedSet(object): def __init__(self): """ Initialize your data structure here. """ self.valToIndex = dict() self.valList = list() def insert(self, val): """ Inserts a value to the set. Returns true if the set did not already cont...
ecee71e834a89bb526f64e9c476b991a1fb231dd
vincent-kangzhou/LeetCode-Python
/328. Odd Even Linked List.py
966
3.875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def oddEvenList(self, head): """ :type head: ListNode :rtype: ListNode """ if head is None or head.next is No...
532928e8d9b64e07656d47861d3ca501c5c5919c
vincent-kangzhou/LeetCode-Python
/024. Swap Nodes in Pairs.py
680
3.75
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ dummyHead = ListNode(None) d...
797abaaaa76f6edf6b1082a8b4d970c9b358f0ae
vincent-kangzhou/LeetCode-Python
/279. Perfect Squares.py
985
3.5
4
from math import sqrt class Solution(object): resultCache = [0, 1, 2, 3] # resultCache[n]==k means n can be represented as sum of k squares def numSquares(self, n): """ :type n: int :rtype: int """ while len(self.resultCache) <= n: m = len(self.resultCache...
cc92c2201f4baedd925a2917265f6c3887f43a47
vincent-kangzhou/LeetCode-Python
/244. Shortest Word Distance II.py
1,274
3.984375
4
class WordDistance(object): def __init__(self, words): """ initialize your data structure here. :type words: List[str] """ self.wordToIndices = dict() # map a word to its indices in words for i,w in enumerate(words): self.wordToIndices.setdefault( w, [] ) ...
8bca58f4c5fa09c6f9fa8b05e090909e104fbaa5
vincent-kangzhou/LeetCode-Python
/255. Verify Preorder Sequence in Binary Search Tree.py
661
3.703125
4
class Solution(object): def verifyPreorder(self, preorder): """ :type preorder: List[int] :rtype: bool """ LB = float("-inf") stack = [] # this is a stack of numbers, x in stack means we have not seen any number after x and >= x # numbers in stack is strickly ...
b3b008d706062e0b068dd8287cfb101a7e268dd9
vincent-kangzhou/LeetCode-Python
/341. Flatten Nested List Iterator.py
2,132
4.21875
4
# """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ # class NestedInteger(object): # def isInteger(self): # """ # @return True if this NestedInteger holds a single integer, rather than a nested list. # :r...
98a8a3d8b5610cc9cdde678712f405914f6e9a4f
vincent-kangzhou/LeetCode-Python
/264. Ugly Number II.py
658
3.59375
4
from heapq import heappush, heappop class Solution(object): def nthUglyNumber(self, n): """ :type n: int :rtype: int """ n -= 1 UNs = [1] # super ugly numbers heap = [(p, p, 0) for p in [2,3,5]] # each item is a 3-tuple (UN, p, idx) # UN is super...
d5e47a9a92a01902e86d30a32166026d92e5a868
vincent-kangzhou/LeetCode-Python
/035. Search Insert Position.py
796
3.890625
4
class Solution(object): def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ # import bisect # return bisect.bisect_left( nums, target ) if not nums or target<nums[0]: return 0 if target...
2348e849ddce735e477df34670440109bf7d8d4f
vincent-kangzhou/LeetCode-Python
/110. Balanced Binary Tree.py
872
3.875
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 isBalancedHelper(self, root): """ return a pair (isBal, depth) """ if root is None: ...
e7e74d4a7a40fb56e8256e7423890fe7c5ade82a
vincent-kangzhou/LeetCode-Python
/364. Nested List Weight Sum II.py
1,542
4.03125
4
# """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ #class NestedInteger(object): # def isInteger(self): # """ # @return True if this NestedInteger holds a single integer, rather than a nested list. # :rt...
75bb760eada467cabec5b79ed49db81f11b65bf3
tchung777/School-Projects
/COEN146_Computer Networks/Lab6/lab6.py
2,695
3.828125
4
import argparse import random import math def generate_file(file_name): """ Here's my docstring for my generate file. If this doesn't get filled in I get - 5. Positional Arguments: file_name is the name of the file, 'w' is for writing, encoding is 'utf-8' because we're usin...
8e16ef4358cd6f773af93aafab475ab8b7a85f96
Shea-Wolfe/what-to-watch
/interface_movie_lib.py
4,319
3.5
4
from movie_lib import * def main(): print('Loading data. Please hold.') get_items() get_users() get_data() current_user = get_user_id() print('\nWelcome user {}.'.format(current_user)) while True: menu_choice = get_menu_choice() if menu_choice == 1: number_of_mo...
eb36a1f18bb74176c9e5d3739f2a7b7353af4afe
bhavin-rb/Mathematics-1
/Multiplication_table_generator.py
655
4.6875
5
''' Multiplication generator table is cool. User can specify both the number and up to which multiple. For example user should to input that he/she wants to seea table listing of the first 15 multiples of 3. Because we want to print the multiplication table from 1 to m, we have a foor loop at (1) that iterates over ...
f4da5bdd691cef34b32b856c9e8c103a3a05a457
ihoover/crypto
/class/2/letter_freq.py
503
3.734375
4
def letter_freq(text): freq_d = {} for c in text: c = c.lower() if c in freq_d: freq_d[c] += 1 else: freq_d[c] = 1 return freq_d def make_pretty(dic): # make copy d = dict(dic) total = 0 for c in d: total += d[c] for c in ...
f491a53e3482fe9b821673104d0e7196a4755aaf
sangee9968/Codekata1-2
/vowel_consonant.py
131
3.84375
4
ch=input() l=['a','e','i','o','u'] if ch not in l: print("Consonant") elif ch in l: print("Vowel") else: print("Invalid")
6c920f2b82c6c2889737dad7130fe265704512aa
NoOneTMFG/PythonProgrammes
/CCC/2706235.py
463
3.59375
4
a = int(input()) b = int(input()) c = int(input()) if a > 100: pa = round((a - 100) * 0.25 + b * 0.15 + c * 0.20, 2) else: pa = round(b * 0.15 + c * 0.20, 2) if a > 250: pb = round((a - 250) * 0.45+b*0.35+c*0.25, 2) else: pb = round(b*0.35+c*0.25, 2) print("Plan A costs " + str(pa)) print("Plan B costs " + str...
63fb9e9ecb33c2251236c32013cfe85238ab362a
NoOneTMFG/PythonProgrammes
/CCC/2706465.py
195
3.703125
4
to = int(input()) v = input() a = 0 b = 0 for x in v: if x == "A": a += 1 elif x == "B": b += 1 if a == b: print("Tie") elif a > b: print("A") else: print("B")
2cab86f9e7b3e833b9bcc812351501e61634c2b2
NoOneTMFG/PythonProgrammes
/CCC/2706533.py
194
3.515625
4
i = 0 n = 0 while i < 6: inp = input() if inp == "W": n += 1 i += 1 if n > 4: print("1") if n == 4 or n == 3: print("2") if n == 1 or n == 2: print("3") if n == 0: print("-1")
1213e266eb4e343e395ed51737c32f4062189ecc
NoOneTMFG/PythonProgrammes
/CCC/2706340.py
112
3.5
4
a = int(input()) b = int(input()) c = int(input()) an = 91 + (a*1+b*3+c*1) print("The 1-3-sum is " + str(an))
d80dabb336d684843c3f0904caa02258be90ae65
WeRockStar/tdd-python-captcha
/operand.py
571
3.890625
4
class Operand(): operand = { 1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine' } class OperandString(Operand): op = 0 ...
378a8cdfc87fe765941e6a133057dd804a98a469
embatbr/noyce
/components/basic.py
3,758
3.625
4
"""Description of diodes and transistors. """ import math class UnsetPinError(Exception): def __init__(self, msg_prefix): self.message = '{} must be set.'.format(msg_prefix) class Pin(object): def __init__(self): self.__voltage = None def __str__(self): ret = '{} Volts'.form...
636b6c984b085e23e4f7e597d6344de83d83c6de
Aleti-Prabhas/HackerRank
/print_function.py
59
3.609375
4
x=int(input()) for i in range (1,x+1): print(i,end="")
401cfd31ef842ac5040118e399dcabbf5c74f462
Hrothgah/Python
/EserciziCamuso/NumeriInteri.py
304
4
4
# Stampa dei quadrati dei primi 10 numeri interi for numero in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: print(numero*numero) print("\nSecondo ciclo for: ") for numero2 in range(1, 11): # l'estremo superiore è escluso print(str(numero2) + ": ", end="") print(numero2*numero2)
4c999d3ab3a3f6835a97911b9c870b88e97865b1
WonderLuc/brother-bootcamp
/python 101/tasks/skeletons.py
2,927
3.625
4
hero = { 'health' : 100, 'damage' : 10 } army = [] id = 0 # Basic functions def createSkeleton(name, health=20, damage=10): global id id = id + 1 return { 'name' : name, 'health' : health, 'damage': damage, 'id': id } def add(skeleton): global army army.append(skeleton) def find(id...
fbdbbedccaefdf9fb2a7b57c8a3920b7c1d499c5
WonderLuc/brother-bootcamp
/python 101/tasks/customerGreeting.py
229
3.84375
4
name = input('Enter customer name\n') print('How may items store have?') number = int(input()) * len(name) print('-------------------') print('Welcome {name}!\nOur store have {number} items'.format(name = name, number = number))
30e17afc24ea935ebb1aee5390464681d9dd1e53
WonderLuc/brother-bootcamp
/python 101/classes.py
1,109
3.71875
4
class MyClass(): x = 5 def showNumber(n): print('Number') my = MyClass() # instance of class my.showNumber() # Number class Animal(): def __init__(self, name, isFlying): self.__name = name self.__isFlying = isFlying def __str__(self): return f'{self.name} is an Animal' @property...
82175f684c9eace2e786622d6ec426883bfe5b39
andytanghr/python-exercises
/PyPart2/triangle2.py
167
4.03125
4
height = int(input('Triangle height? ')) width = 1 for row in range(height): print(' ' * height + '*' * width + ' ' * height) width += 2 height -= 1
6151c84148925bf7adc36e41399561cbdf30ce20
andytanghr/python-exercises
/PyPart2/leetspeak.py
357
3.828125
4
string = input('Input text to convert to l33tspeak: ') leetDict = { 'A': '4', 'E': '3', 'G': '6', 'I': '1', 'O': '0', 'S': '5', 'T': '7' } stringLeet = '' for character in string: if character.upper() in leetDict: stringLeet += leetDict[character.upper()] else: strin...
88c7885391ac5743954ee2d6e74ae5512ed15fe3
andytanghr/python-exercises
/PyPart2/factor.py
154
4.0625
4
factorMe = int(input('What number to factorize? ')) for factor in range(1, factorMe+1): if factorMe % factor == 0: print(factor) print(-factor)
eef6d1f8732d965778a359388937e26af19c8153
andytanghr/python-exercises
/PyPart2/multiplicationTable.py
216
3.875
4
for multiplicand in range(1, 11): for multiplier in range(1, 11): product = multiplicand * multiplier print(str(multiplicand) + ' X ' + str(multiplier) + ' = ' + str(product)) # 1 to 10 # 2 to 10 # 3 to 10
ac5acc74b5275738bd8a5eb40161f5098ea681ff
andytanghr/python-exercises
/PyPart1/madlib.py
285
4.25
4
print('Please fill in the blanks below:') print('Hello, my name is ____(name)____, and today, I\'m going to ____(verb)____.') name = input('What is your name? ') verb = input('What action do you take? ' ) print('Hello, my name is {}, and today, I\'m going to {}.'.format(name, verb))
eadbaf6c86db311689dc044b4b9254b126ad8800
Elijah-Code/Algorithms-and-DS
/hashmap.py
2,208
3.734375
4
class HashMap: def __init__(self): self.size = 2 self.hash_map = [None]*self.size self.vals = [None]*self.size self.next_free = 0 def add(self, key, val): if self.next_free >= self.size: print("Something went wrong") return index = hash(...
b05e6ae27d57fd49b688b4b8172eebbd2baae56d
GhostForce/GhostForce
/my_pool.py
2,603
3.609375
4
from multiprocessing import Process, Queue import time """ Found this beauty on reddit. Cheers to the orig author. """ class Pool(object): """Very basic process pool with timeout.""" def __init__(self, size=None, timeout=15): """Create new `Pool` of `size` concurrent processes. Args: ...
8b778a432a66f0d260fafe7655461e1e9453e0fc
soujanya1129/AITPL2125
/notepad.py
1,329
3.671875
4
#create a window like notepad from tkinter import * a=Tk() a.title("untitled - notepad") a.geometry("500x500+100+100") m1=Menu() l1=Menu() l1.add_command(label="New") l1.add_command(label="New Window") l1.add_command(label="Open...") l1.add_command(label="Save") l1.add_command(label="Save As...") l1.add_com...
4bde10e50b2b57139aed6f6f74b915a0771062dd
Ayesha116/cisco-assignments
/assigment 5/fac1.py
869
4.6875
5
# Write a Python function to calculate the factorial of a number (a non-negative # integer). The function accepts the number as an argument. def fact(number): factorial = 1 for i in range(1,number+1): factorial = factorial*i print(factorial) fact(4) # ...
4801ff9cb5d83bd385b3f650a3ba808d7f3cf229
Ayesha116/cisco-assignments
/assigment 5/market6.py
670
4.34375
4
# Question: 6 # Suppose a customer is shopping in a market and you need to print all the items # which user bought from market. # Write a function which accepts the multiple arguments of user shopping list and # print all the items which user bought from market. # (Hint: Arbitrary Argument concept can make this ta...
737c8d15876ea1c6cf897d21b9e96dd7be2fe5d8
Ayesha116/cisco-assignments
/assigment 3/calculator.py
504
4.1875
4
# 1. Make a calculator using Python with addition , subtraction , multiplication , # division and power. a =int(input("enter first value:")) b =int(input("enter second value:")) operator =input("enter operator:") if operator=="+": print("answer=",a+b) elif operator=="-": print("answer=",a-b) elif opera...
7866fcfad84a2b9f80d961d0e011c7259a6ea7e9
ponyatov/metaLold
/book/prolog/yield01.py
189
3.546875
4
import time def now(): while True: yield time.localtime() var = now() ## get iterator def main(): for item in [1,2,3,4,5]: print item, var.next() ## lazy! main()
d7f20fbdee7d28a99591ab6bc4d3baf14f4a1920
aarizag/Challenges
/LeetCode/Algorithms/longest_substring.py
747
4.1875
4
""" Given a string, find the length of the longest substring without repeating characters. """ """ Example 1: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. """ def lengthOfLongestSubstring(s: str) -> int: letter_locs = {} cur, best, from_ind = 0, 0, 0 ...
32f238af97f3f5cfe45627b38c92cb5a8dbfdcb1
aarizag/Challenges
/DailyProblem/Math/rand7.py
402
4.09375
4
""" This problem was asked by Two Sigma. Using a function rand5() that returns an integer from 1 to 5 (inclusive) with uniform probability, implement a function rand7() that returns an integer from 1 to 7 (inclusive). """ from random import randint def rand5(): return randint(1, 5) def rand7...
6cb91d091f7ccf9b450b9c375da1549725a1db94
migonzalvar/mfs2011-practicum-saas
/report/snippets/operations.py
414
3.71875
4
from interval import Interval def slots_in_interval(length, interval, step=None): step = length if step == None else step return (Interval(s, s + length) for s in range(interval.start, interval.end, step) if s + length <= interval.end) def interval_overlaps(interval, intervals): ...
b58652d88c93a585645df9f52551f390ca910b16
ritishadhikari/matplotlib
/matplotlib_axis_labels_legend_grid.py
480
3.515625
4
import matplotlib.pyplot as plt days=[1,2,3,4,5,6,7] max_t=[50,51,52,48,47,49,46] min_t=[43,42,40,44,33,35,37] avg_t=[45,48,48,46,40,42,41] plt.plot(days,max_t,label ='Maximum Temperature') plt.plot(days,min_t, label = 'Minimum Temperature') plt.plot(days,avg_t, label ='Average Temperature') plt.xlabel("Day...
ab2768ae8c3628ddc7523ff4c64045b61be22d1d
harish-515/Python-Projects
/ErrorDebugging/Exceptions.py
223
3.5625
4
a = 1 b = "2" #print(int(2.5) print(int(2.5)) """ PS E:\Python-Projects\Python-Projects\ErrorDebugging> python exceptions.py File "exceptions.py", line 4 print(a+b) ^ SyntaxError: invalid syntax """ print(a+b)
052bcd3e8b2293371303450d3281f56c98498521
harish-515/Python-Projects
/Tkinter/script1.py
1,203
4.375
4
from tkinter import * #GUI are generated using window & widgets window = Tk() """ def km_to_miles(): print(e1_value.get()) miles = float(e1_value.get())*1.6 t1.insert(END,miles) b1=Button(window,text="Execute",command=km_to_miles) # pack & grid are used to make these button to visible b1.grid(row=0,c...
bc8caa8e100057d4a9dd9f23402e1d4013ec95ef
Flyduckbb/Python
/6066.py
214
3.8125
4
a,b,c=input().split() a=int(a) b=int(b) c=int(c) if a%2 == 0: print("even") else: print("odd") if b%2 == 0: print("even") else: print("odd") if c%2 == 0: print("even") else: print("odd")
ba0fb3a0d0894635ef585cd3374aa61d0ab64c2e
meetali98/Python-Basics
/Functions.py
270
3.59375
4
# FUNCTIONS ---> allows us to create block of code than can be easily many times, #without needing to constantly rewrite the entire block of code def say_hello(name='default'): # uses default when no parameter is passed print(f'hello {name}') say_hello('Meetali')
a3425e3b3a4618b032be4af3202b83c1b72e65f7
pacobarter/testing-pygame
/ai/objects.py
2,805
3.578125
4
# -- coding: utf-8 -- # ============================================================================= # # objects.py # (c) 2011 rjimenez ...
5daf750e42f90d6f29ade4121d6c29c80ff0c3e2
BrianArb/stanford-design-and-analysis-algorithms
/merge_sort.py
3,120
4.28125
4
#!/usr/bin/env python """ Merge sort is an O(n log n) comparison-based sorting algorithm. Most implementations produce a stable sort, which means that the implementation preserves the input order of equal elements in the sorted output. Mergesort is a divide and conquer algorithm that was invented by John von Neumann i...
6d58e0595f533e6d75d337ba67991793f93ed5f5
angeleslf99/Cuota.py
/recibo/amigos.py
263
3.625
4
#esto es estructurado numero = 3738 suma = 0 """la letra i solo define un valor, puede ser cualquier letra""" for i in range(1, numero, 1): if (numero % i) ==0: print (i, 'es divisor') suma += i print ('la suma de los divisores es: ', suma)
3c980db5c51175aaac51f32abb0cb5522fd1bcc1
AxelPliopas/Teste2
/app.py
939
3.984375
4
# First Homework: N-first prime numbers print('--------------------------------------------------') N = int(input("How many first prime numbes you want to show: ")) nFound=0 num=2 while nFound<N: isPrime=1 for i in range(2,num): if (num % i)==0: isPrime=0 break if isPrime==1...
447a9c981e1744056f4e993d27dda735f436e6b5
NicholasTing/CSInterviewQuestions
/Cracking_The_Coding_Interview/Array_And_Strings/test.py
400
3.84375
4
prime_numbers = {} def isPrime(number): for i in range(2,number): if number % i == 0: return False return True number = 50 answer_found = 0 for i in range(2, number): first = isPrime(i) second = isPrime(number - i) if (first and second): prin...
32834485aa18691625b457a2026542484fbdaa00
Futrell/rfutils
/rfutils/classifiers/randomclassifier.py
473
3.515625
4
""" A classifier that makes random predictions. Useful as a mockup. """ import random import classifier class RandomClassifier(classifier.Classifier): def __init__(self, classes, **parameters): super(RandomClassifier, self).__init__(**parameters) self.classes = classes def _classify(s...
2aca735a1d0f7bf79cb7a6421bb6c69c0241e2cf
Futrell/rfutils
/rfutils/myrandom.py
3,105
4.40625
4
import itertools as it import math from random import * from .compat import * def prob_choice(iterable, key=None): """ choice by probability Choose an element from iterable according to its probability. Interface can be used similarly to max, min, sorted, etc: * If given an iterable of (probabil...
92b0e9f196ffcf01efe68ec65bfd9f1144e9c2ac
unixonboard/Python_Scripts
/Hacker_rank/Practice.py
564
3.71875
4
# print("hello") def sample(): print("i'll print this no matter") return sample() def calculator(a,b): # var=a+b return a+b sum=calculator(10,5) print(sum) employee={'thakur':1,'priya':2} def test(emp): new={'nandu':3} print("value",new) return new funcvalue=test(employee) print("out func...
c17681d20a2b0b8a2c11b9ddb92bf590e2c1a1d7
unixonboard/Python_Scripts
/while_loop.py
89
3.703125
4
var=1 while (var<=10): print("Hi i am ", var) var=var+1 print("") print("Good Bye!")
e12e8d5cfca1a76ec21fe99412e7589264b9d7fa
val2k/algorithms
/sort/quicksort.py
291
3.828125
4
#!/usr/bin/python3.4 def quicksort(liste): if liste == []: return [] pivot = liste.pop(0) bigger = list(filter(lambda x: x > pivot, liste)) smaller = list(filter(lambda x: x <= pivot, liste)) return (quicksort(smaller) + [pivot] + quicksort(bigger))
e08fc50157df9d814010f78f15003bf17b96bc56
dadnotorc/orgrammar
/src/lintcode/_2454_N_threads_to_find_the_number_with_most_factors/python/solution.py
2,322
3.828125
4
""" 2454 · N threads to find the number with most factors Easy #Thread Pool This problem requires you to start n threads to find the number with the most factors in the interval [1, m]. If there are multiple numbers with the most factors, find the largest one. Write the find_num_with_most_factors (findNumWithMostFact...
268040a0b85eb2039026a3bf495bc863fc745bab
dadnotorc/orgrammar
/src/python/_2312_Combine_keys_values_into_new_list/solution.py
357
3.515625
4
def composition(dict_1: dict) -> list: ''' :param dict_1: Input dictionary :return: A new list of keys and values in the dictionary ''' result = [] for k, v in dict_1.items(): result.append(k) result.append(v) return result # return [key if j ^ 1 else value for key, val...
8d0c552ec330b8b39f8fe2ffdf27bf8f4f207842
dadnotorc/orgrammar
/src/python/main.py
190
3.875
4
num_str = input("num?\n") if not isinstance(int(num_str), int): raise TypeError("not a int") len = len(num_str) ans = 0 for i in range(len): ans += int(num_str[i]) print(ans)
b7ec6fb0a5abd7ca6c7991c6de2f71c8c44fb173
jamesbland123/opscli
/opscli/command.py
1,672
3.578125
4
""" Command class """ import argparse import sys import importlib import pprint class Command(): """ This is a Command class to process subcommands for the cli. Attributes: None """ def __init__(self): """ Constructor for Command class that parses cli subcommands a...
7d9fa83810e6e05e4362aa4a32b5a0e901421495
protea-ban/LeetCode
/000.Rookie/1-1乱序字符串检查.py
1,688
3.921875
4
""" 乱序字符串是指一个字符串只是另一个字符串的重新排列。例如,'heart' 和 'earth' 是乱序字符串。'python' 和 'typhon' 也是。为了简单起见,我们假设所讨论的两个字符串具有相等的长度,并且他们由 26 个小写字母集合组成。 """ # 解法1:检查 def anagramSolution1(s1, s2): a_list = list(s2) pos1 = 0 stillOK = True while pos1 < len(s1) and stillOK: pos2 = 0 found = False while...
93619b6d9eec4db8d6f83bc3dcf4c189374b956d
protea-ban/LeetCode
/231.Power of Two/Power of Two.py
464
3.75
4
class Solution: def isPowerOfTwo(self, n): """ :type n: int :rtype: bool """ if n < 0: return False hasOne = False while n > 0: if n & 1: if hasOne: return False else: ...
080a1a74fe69eca3cf5add4d0200e16d976d1dd7
protea-ban/LeetCode
/066.Plus One/Plus One.py
425
3.515625
4
class Solution: def plusOne(self, digits): """ :type digits: List[int] :rtype: List[int] """ # 整数列表转成整数 num = int(''.join([str(t) for t in digits])) # 加一 num += 1 # 将整数转成列表 return [int(s) for s in str(num)] if __name__ == '__main__': ...
74aceb8b8ad1c9099d32176951c2a19dbcf7bfa7
protea-ban/LeetCode
/242.Valid Anagram/Valid Anagram.py
981
3.71875
4
# -*- coding: utf-8 -*- # @Time : 2019/9/2 11:15 # @Author : banshaohuan # @Site : # @File : Valid Anagram.py # @Software: PyCharm # 排序法 O(NlogN) class Solution(object): def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ return sorted...
f96a168071a6d1504455caf92c7dd92038204d4a
JoeJung27/Zerojudge
/Zerojudge/a024.py
280
3.703125
4
def gcd(a,b): while b: r = a%b a = b b = r return a while 1: try: numbers = input() tmpn1 = int(numbers.split()[0]) tmpn2 = int(numbers.split()[1]) print(gcd(tmpn1,tmpn2)) except: break
6668dc6dbdb1ef3f599ef07e6d16768496ce6b4d
JoeJung27/Zerojudge
/Zerojudge/a003.py
167
3.53125
4
a = input() b = a.split() m = b[0] d = b[1] s = (int(m)*2+int(d))%3 if s == 0: print("普通") if s == 1: print("吉") if s == 2: print("大吉")
77254cf8c150a314852fa41dfda981e42ea6eba1
ShiraNegbi/Multi-Objective-Optimization
/MultiObjectiveOptimization2.py
3,191
4.15625
4
import datetime import random # The class represents job position and its characteristics that are relevant for someone who looks for a job class job(): def __init__(self, id_number, salary_per_month, distance, entrance_date, working_hours): self.id_number = id_number self.salary_p...
8c3f9404e7cc21a4ae04f2c1d94a62f63daf7224
nocotan/HackerRank
/Python/Strings/swap_case.py
149
4.0625
4
string = str(input()) ans = "" for s in string: if(s.islower()): ans += s.upper() else: ans += s.lower() print(ans)
d8b321544ab092793e10f72194f33b176397959b
nocotan/HackerRank
/Tutorials/30DaysOfCode/Python/Day02.py
208
3.890625
4
cost = float(input()) tip_per = int(input()) tax_per = int(input()) tip = cost * tip_per / 100 tax = cost * tax_per / 100 total = cost + tip + tax print("The total meal cost is %d dollars." % round(total))
acc68fe2d4bfeaefa3e577fd40611cad32067121
nocotan/HackerRank
/Python/Introduction/marks.py
254
3.5
4
n = int(input()) dic = {} for i in range(0, n): line = input().split() name = line[0] a = float(line[1]) b = float(line[2]) c = float(line[3]) ave = (a + b + c) / 3 dic[name] = ave key = str(input()) print("%.2f" % dic[key])
c932c15d1ecdfe595d96f532b83a11d02a9ef341
oclaumc/Python
/ex001ex002.py
431
4.3125
4
#Desafio 1 e 2 #Hello World / Exibir / inserção de variaves / formatação de objetos nome = input ("Qual seu nome?") print ("olá {}, prazer te conhecer!".format(nome)) print ("Qual sua data de nascimento?") dia = input ("Dia:") mes = input ("Mês:") ano = input ("Ano") #print ("Você nasceu no dia",dia,"do mês",mes,"do a...
82a1953bd3ca9f1a55e38c9ac5952d8183c912a3
hellboy0621/beautysoup
/decorator_test.py
4,790
3.71875
4
''' 简单装饰器 ''' import functools import time def my_decorator(func): def wrapper(): print('wrapper of decorator') func() return wrapper @my_decorator def greet(): print("hello world") #原始调用无需@装饰器名 # greet=my_decorator(greet) # greet() #wrapper of decorator #hello world #优雅调用,在被装饰函数前加@装饰器...
51f27da75c6d55eeddacaa9cef05a3d1d97bb0db
r-fle/ccse2019
/level3.py
1,500
4.21875
4
#!/usr/bin/env python3 from pathlib import Path import string ANSWER = "dunno_yet" ########### # level 3 # ########### print("Welcome to Level 3.") print("Caeser cipher from a mysterious text file") print("---\n") """ There is text living in: files/mysterious.txt You've got to try and figure out what the secret mes...
4881969f35146659b665d49a8c96fb5939050c73
t-morisawa/gof-python
/memento/wadayama.py
607
3.5625
4
from calc import Calc # 計算する和田山君クラス。 class Wadayama: def __init__(self): self.map_ = {} if __name__ == "__main__": wdym = Wadayama() calc = Calc() for i in range(1, 6): calc.plus(i) print(calc.getTemp()) wdym.map_["5までの足し算"] = calc.createMemento() # 数日経過 # 10までの足し算を...
d30c4685534e493a4261040d83ee6e1cd182e169
t-morisawa/gof-python
/bridge/TimerSorter.py
237
3.5
4
from datetime import datetime from Sorter import Sorter class TimerSorter(Sorter): def timerSort(self, list_): start = datetime.now() self.sort(obj) end = datetime.now() print("time:"+(end - start))
b86c0da36a1753cb0a080ff7e34a2e5ce55c0eb4
Freddsle/rosalind_tasks
/task_004.py
278
3.5625
4
#Rabbits and Recurrence Relations http://rosalind.info/problems/fib/ with open("rosalind_fib.txt", "r") as f: n, k = (int(value) for value in f.read().split()) pairs_1, pairs_2 = 1, 1 for i in range(n-2): pairs_1, pairs_2 = pairs_2, pairs_1*k + pairs_2 print(pairs_2)
e2c1bb83fff775c6134ccfb853433f7e96445d70
richard-G/chess
/chess.py
24,424
3.609375
4
# Chess class Piece: def __init__(self, colour): self.colour = colour self.is_alive = True def move(self, target_indices): # check first if move is allowed if True: self.position[0] = target_indices[0] self.position[1] = target_indices[1] # general...
8b8bd85ec48ddd120a6438354affb7372e689c99
Sparkoor/learning
/start/collectionsTest.py
1,708
4.125
4
""" collections测试 """ from collections import namedtuple p = (1, 2, 3, 4, 5) print(type(p)) print(p) # 可以定义坐标之类的,并且保证不可变,Point tuple的一个子类 Point = namedtuple('name', ['x', 'y']) print(Point) # <class '__main__.name'> name的一个实例 print(type(Point)) p = Point(1, 2) print(p) q = Point(2, 3) print(q) # 使用list存储数据时,按索引访问元素很...
4d21aaca5ef832c47cf493a0ee766e0370cf88cb
Sparkoor/learning
/start/originFunc/aboutItertools.py
890
3.96875
4
""" python的内建模块itertools """ import itertools def test1(): """ 无限的迭代 :return: """ natuals = itertools.count(1) for i in natuals: print(i) def test2(): """ 重复迭代 """ cs = itertools.cycle("abc") def test3(): natuals = itertools.count(1) # takewhile 可以截取有限序列 ...
0a1096fde4d17dcf3a71581f05ffe3297cdb9bb4
Sparkoor/learning
/start/mysqltest/SqlAichemy.py
1,158
3.78125
4
""" ORM框架 """ class user2(object): def __init__(self, id, name): self.id = id self.name = name # 导入sqlalchemy,并初始化DBSession from sqlalchemy import Column, String, create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base # 创建对象基类 Base = decl...
cde2be9e1e63bcf660cd3b22bb02970399931cd5
Sparkoor/learning
/CommonTest.py
939
3.640625
4
aa = (1, 2, 3, 4) print(type(aa)) bb = {1, 2, 3, 4, 5} print(type(bb)) cc = set([1, 2]) print(cc) # dict是这样定义的 dd = dict(na='a', d='c') print(dd['d']) tree = {'root': {'chil1': {'grandson1': 'maxiu', 'grandson2': 'liyliy'}, 'child2': 'jerry'}} print(tree.keys()) print(tree.values()) tree2 = list(tree.values()) print(t...
deb05ec793a2c4a0967862f916fed512abe816ae
Sparkoor/learning
/leetcode/LongestPalindrome.py
1,606
3.65625
4
class Solution: def longestPalindrome(self, str1, str2): """ 这是求最长公共子串 :param str: :return: rstr """ ne = self.maxCommonLength(str2) n, m = len(str1), len(str2) i, j = 0, 0 # str1 = 'ADACADDDDAVV' # str2 = 'ADD' while i < n and ...
64c8e3ccc97975251c9ac96fd7180357b341575e
Sparkoor/learning
/leetcode/ContainsDuplicate.py
956
3.71875
4
""" 判断有无重复数字, 先排序再判断 """ class Solution: def containsDuplicate(self, nums): """ :type nums: List[int] :rtype: bool """ nums.sort() length = len(nums) if length == 0: return False if length == 2 and nums[0] == nums[1]: return T...
edffbeb788e8e67af4bf05c58dbe483f4515a912
Sparkoor/learning
/machineLearning/cha2/thistest.py
106
3.671875
4
arr = [2, 3, 1, 1, 35, 6] for a in iter(arr): print('a', a) import numpy as np aa = np.array([1, 1])
a6c6786ffca4f3f21eb78d348fd2afad99bbcc94
Sparkoor/learning
/mooc/FirstTryByOthersExample.py
2,601
3.546875
4
""" 实现单层神经网络 """ import numpy as np # 加载数据集 def load_dataset(): pass # 激活函数 ReLU函数 f(x)=MAX(0,X) def ReLU(z): mz, nz = z.shape zero = np.zeros(mz, nz) return np.maximum(zero, z) # sigmoid函数 def sigmoid(z): return 1.0 / (1 + np.exp(z)) # 将四位数组转换成2维数组,在这不知道,元素数据的结构是什么,没办法理解 def tansformArr...
cc2f788593916288044904aedcd2da9e39a1246e
Sparkoor/learning
/machineLearning/cha5/linerRegression.py
974
3.75
4
""" 线性回归,对代价函数使用梯度下降法 """ import numpy as np def errorFunc(theta, x, y): """ 代价函数,使用的是距离 :param theta: :param x: :param y: :return: """ m = len(theta) diff = np.dot(theta, x.T) - y return (1 / 2) * (1 / m) * diff ** 2 def derivativesFunc(theta, x, y): """ 计算代价函数的导函数 ...
ae76a2dff300763384c50deb6ad8359a8871a57a
Sparkoor/learning
/leetcode/p/test4.py
2,269
3.609375
4
class Solution: ## def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ n = len(nums) for i in range(0, n): for j in range(i + 1, n): if nums[i] > nums[j]: ...
181da3ded6c4d5b254727745570b80cdd4d26dd2
acaciamoran/amoran05
/project4/finder_funcs.py
2,605
3.6875
4
# Name: Acacia Moran # Course: CPE 101 # Instructor: Nupur Garg # Assignment: Project 1 # Term: Spring 2017 def get_rows(puzzle_string): list_of_strings = [] for i in range(10): start = i * 10 end = (i+1) * 10 row_string = get_row(puzzle_string, start, end) list_...
8857dd424a27a3e3165a90f10c90980d8dabf32c
acaciamoran/amoran05
/project4/wordfinder.py
819
3.8125
4
# Name: Acacia Moran # Course: CPE 101 # Instructor: Nupur Garg # Assignment: Project 4 # Term: Spring 2017 from finder_funcs import * def main(): puzzle_string = input() list_of_words = input() print("Puzzle:\n") list_of_puzzle = get_rows(puzzle_string) for characters in...
4481af310834026f36072d4283958c84145c4664
totetmatt/project-euler
/03 - Largest prime factor/main.py
288
3.5
4
number = 600851475143 import math def isPrime(n): for j in range(int(n/2)+1,2,-1): if n % j == 0: return False return True i = int(math.sqrt(number)) while i: if number % i == 0: if isPrime(i): print(i) break i -=1
5bf74bb0eaa4de6211b2c8c5702505c1a701f572
abhideshmukhis/hackerrank
/Compare_the_triplets.py
737
3.515625
4
#!/bin/python3 import math import os import random import re import sys # Complete the compareTriplets function below. def compareTriplets(a, b): ascore = 0 bscore = 0 for i in range (0, 3, +1): if a[i]>b[i]: ascore = ascore + 1 elif a[i]<b[i]: bscore = ...
e1598dd515c0ae73518aeac831743ed8243ebdcd
evanqianyue/AppiumPython
/Case/nameqyt.py
715
3.78125
4
class Test(): def __init__(self, a, b): self.a = int(a) self.b = int(b) def print_out(self): print("print_out:", self.a + self.b) @classmethod def classmethod_sum(cls, a, b): cls.a = int(a) cls.b = int(b) print('classmethod_sum:', cls.a + cls.b) @st...
d718e243f60ab7844ccc2ebdbeb0236669420cd7
liuxiangjuncs/MachineLearning
/LinearRegression/linear_regression.py
5,904
4.4375
4
import math import numpy as np import matplotlib.pyplot as plt class LinearRegression(object): """ An easy implementation of linear regression algorithm in machine learning. Form of prediction function is f(x) = w * basic_function(x) is linear in w. So called linear regression And this algorithm ...