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
bafcfb78e38c42cf6c23be6f509de455a905319b
mezla/6001x
/Part 1/secret_num.py
685
4.09375
4
print 'Please think of a number between 0 and 100!' epsilon = 1 step = 1 low = 0 high = 100 ans = (high+low)/2 while abs(ans**2-100) >= epsilon: print 'Is your secret number ' + str(ans) + '?' info = str(raw_input('Enter \'h\' to indicate the guess is too high. Enter \'l\' to indicate the guess is t...
4a610288128ebf5377b29cba18ea047633b340f5
mezla/6001x
/Part 1/quiz/p5.py
693
3.984375
4
def laceStrings(s1, s2): """ s1 and s2 are strings. Returns a new str with elements of s1 and s2 interlaced, beginning with s1. If strings are not of same length, then the extra elements should appear at the end. """ if not s1 or not s2: if not s1: return s2 ...
00708ba1d213c584d475ca099e6be832a27fac0c
mezla/6001x
/Part 1/quiz/p7_div_try_2.py
608
3.9375
4
def McNuggets(n): """ n is an int Returns True if some integer combination of 6, 9 and 20 equals n Otherwise returns False. """ x = 1 while True: if n%20 == 0: return True elif n%9 == 0: return True elif n%6 == 0: ret...
9723db9bc6f9d411d0ae62f525c33a410af9f529
george-ognyanov-kolev/Learn-Python-Hard-Way
/44.ex44.py
981
4.15625
4
#inheritance vs composition print('1. Actions on the child imply an action on the parent.\n') class Parent1(object): def implicit(self): print('PARENT implicit()') class Child1(Parent1): pass dad1 = Parent1() son1 = Child1() dad1.implicit() son1.implicit() print('2. Actions on the child overr...
04ed69a5fdc6f03188549846aa98dff194753490
Coder1900/guessing_game
/main.py
3,089
4.15625
4
import random import my_input_library as myinputs # creates a random number and asks user to guess it # the input is the number range to guess_random_number # output is number of trys def guess_random_number(upper_limit): trys = 0 guess = "" number_generator = random.randint(0, upper_limit) while guess != num...
26c234de72edc6fcfa981194814c814e40bc7bed
chuzhinoves/DevOps_python_HW4
/6_a.py
940
3.796875
4
""" 6. Реализовать два небольших скрипта: а) итератор, генерирующий целые числа, начиная с указанного, Подсказка: использовать функцию count() и cycle() модуля itertools. Обратите внимание, что создаваемый цикл не должен быть бесконечным. Необходимо предусмотреть условие его завершения. Например, в первом задании выв...
fa6e8dd7c6f9f9279cb60f469fbaaf5a2a8bc686
kritikadusad/AlgorithmsForDNASequencing
/shortest_common_superstring.py
3,797
4.0625
4
import itertools def overlap(a, b, min_length=3): """ Return length of longest suffix of 'a' matching a prefix of 'b' that is at least 'min_length' characters long. If no such overlap exists, return 0. """ start = 0 # start all the way at the left while True: start = a.fi...
e5663cb79ea48d897aacc4350443c713dee27d5e
jejakobsen/IN1910
/week1/e4.py
773
4.15625
4
""" Write a function factorize that takes in an integer $n$, and returns the prime-factorization of that number as a list. For example factorize(18) should return [2, 3, 3] and factorize(23) should return [23], because 23 is a prime. Test your function by factorizing a 6-digit number. """ def get_primes(n): numb...
8e1f774d2d8748ae9f0a7707208ebf6e77ca8f7a
Yousab/parallel-bubble-sort-mpi
/bubble_sort.py
981
4.1875
4
import numpy as np import time #Bubble sort algorithm def bubble_sort(nums): # We set swapped to True so the loop looks runs at least once swapped = True while swapped: swapped = False for i in range(len(nums) - 1): if nums[i] > nums[i + 1]: # Swap the elements ...
213560426ae3dcc15c94f6e262f8a1f5dd34261d
camillemura100t/DevOps_training
/python_training/f_pair_impair.py
423
3.765625
4
#!/usr/bin/env python3.8 #=> module def pair(valeur1): if valeur1 % 2 == 0: return True def impair(valeur2): if valeur2 % 2 != 0: return True #var1 = int(input("Entrer un nombre entier: ")) #if pair(var1): # print("La fonction pair retourne True pour la valeur %d" %var1) #elif impair(var1...
faa9a84da62da62e5c6b3f9038f71a6b811e0e95
camillemura100t/DevOps_training
/python_training/boucle_test_vanessa.py
446
3.5625
4
#!/usr/bin/env python3.8 liste_produit = ['chaussure', 'pain', 42, 'chocolat'] taux_tva = 19.6 taux_tva_bas = 5.5 liste_prix = {} for produit in liste_produit: if produit == 'pain': liste_prix[produit] = taux_tva_bas * 10 continue elif type(produit) != str: print(type(produit)) ...
3fb47ab2714c6447b691f3954d9b0a5cfafeea9f
eodenyire/AirBnB_clone-7
/models/city.py
469
3.5625
4
#!/usr/bin/python3 from models.base_model import BaseModel ''' This is the 'city' module. city contains the class 'City', which is a sub-class of BaseModel. ''' class City(BaseModel): '''This is the 'City' class. City contains two public attributes: 'state_id' and 'name'. ''' state_id = '' name ...
9ca106196ffdc6c26580d1d472cf6ee4964fcf51
eodenyire/AirBnB_clone-7
/tests/test_models/test_city.py
1,284
3.515625
4
#!/usr/bin/python3 ''' This is the 'test_city' module. test_city uses unittest to test the 'models/city' module. All credit for this module goes to Danton Rodriguez (https://github.com/p0516357) ''' import unittest from models.city import City import datetime class TestCity(unittest.TestCase): """Test for City c...
20f6be3633b3373d6e38a236c326f75029d536f7
Amruthglr/PythonPrograms
/Day6/Program2.py
491
4.0625
4
# A Python Program to UnderStand Instance variable class Student: def __init__(self,name ='', age=0, marks=0): self.firstname = name self.age = age self.marks = marks sayali = Student('Sayali', 25, 90) print(sayali.firstname) print(sayali.age) print(sayali.marks) print("\n") amruth = St...
232896bfb010b367fdc7bbfc0c51b56d32208a1b
Amruthglr/PythonPrograms
/Day1/Program2.py
338
4.4375
4
age = int(input("Enter your AGE: ")) if age > 18 : print("You are eligible to vote") print("vote for your favourite candidate") else: print("You still need to wait for {} years".format(18-age)) # Another way to write if age < 18: print(f"You nedd still wait for {18-age} years") else: print("your e...
a79063252fdcad3f5e7072ab714ccd1252d37b03
Amruthglr/PythonPrograms
/Day3/Program4.py
245
3.875
4
#More on While Loops Exits_available = ["East", "North", "South", "West"] choosen_Exit = "" while choosen_Exit not in Exits_available: choosen_Exit = input("Enter the where do you want to exit : ") print("arent you glad you got out out ")
3f6087ca9c827cc0f25c0dcb75b0d41559fc6887
Amruthglr/PythonPrograms
/Day3/Program3.py
170
3.96875
4
# for Loop and While Loop for i in range(10): print("Now value of the i is {}".format(i)) i = 0 while i < 10: print("value of the i is {}".format(i)) i += 1
8f112c6bb2afdfba7f267b2196c36449b55d5524
dpp1013/TC-track-prediction-based-on-multi-model-data
/Compare/model_RNN.py
789
3.90625
4
''' RNN模型 ''' import torch import torch.nn as nn import numpy as np TIME_STEP = 16 # rnn time step INPUT_SIZE = 4 # rnn input size LR = 1e-3 # learning rate # LSTM class RNN(nn.Module): def __init__(self): super(RNN, self).__init__() self.lstm = nn.LSTM(6, 6, 3) # 输入数据2个特征维度,6个隐藏层维度,2个LSTM串联,...
84402d8e4aa8d594dc246331a7677b1d766cacb4
yatingupta10/Coding-Practice
/LeetCode/872_Leaf_Similar_Trees.py
1,050
3.9375
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 leafSimilar(self, root1, root2): """ :type root1: TreeNode :type root2: TreeNode :rty...
f8ea97b39b452682581643011d5a73755a678cb7
Kornvalles/Python4sem
/week_7/exercise_human.py
424
3.734375
4
import string class InvalidArgumentException(Exception): pass class Person(): def __init__(self, name): self.name = name def check_name(self): for char in self.name: if char in string.ascii_letters and char.isupper(): return True else: ...
98740e2a4a20e89d81f006e44d63aa333ef2a2d1
Kornvalles/Python4sem
/week_14/regression.py
586
3.5625
4
import sklearn.linear_model import pandas as pd import numpy as np data = pd.read_csv("/Users/mikkel/Git/Python4sem/week_14/car_sales.csv") data.plot.scatter(x=1, y=2) xs = data['GDP(trillion)'] ys = data['4wheeler_car_sale'] xs_reshape = np.array(xs).reshape(-1, 1) print(xs.shape) print(xs_reshape.shape) model = skl...
e8ce59255c8c2e48ba1536a0f59185baef9a04cf
BrandonShute/President
/president/players/base_player.py
1,447
3.640625
4
from abc import ABC, abstractmethod from gameplay.president_card import PresidentCard class BasePlayer(ABC): def __init__(self, name: str, is_computer: bool = False): self.name = name self.is_computer = is_computer self.__cards = [] @property def cards(self) -> list: ret...
d73f0bc73e06971c0f6af781d515cd88a40342b4
rocciares/python-12
/maye/1.py
191
3.921875
4
name=input() if name=="alice": print("hi,alice") elif age < 12: print("you ae not alice,kiddo.") else: print("you ar10000 朱国鹏 孟响e neither alice nor a little kid") alice
655158484a1949936386badac352f2ae00d7d420
mccarvik/poker
/app/deck_utils/deck.py
710
3.546875
4
import pdb from app.deck_utils.card import Card class Deck(): ''' Class to represent a deck of cards ''' SUITS = ['s', 'h', 'c', 'd'] VALUES = ['A', 'K', 'Q', 'J', '10', '9', '8', '7', '6', '5', '4', '3', '2'] def __init__(self): self.initialize() def initialize(self): ...
8f8d2783f87e8a23018d6a7eb299b782834993b8
Euphyzr/ProjectEuler
/Python/006.py
698
3.890625
4
""" Sum square difference ~~~~~~~~~~~~~~~~~~~~~ The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10) ^ 2 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the...
656fca75a084a754fff675894dd551971299d765
Euphyzr/ProjectEuler
/Python/010.py
122
3.734375
4
from utils import is_prime _sum = 0 for n in range((2 * (10 ** 6))+1): if is_prime(n): _sum += n print(_sum)
8f3eee735f0be5000162766be3de74c62effddf9
conor36/AI-Landmark-Recognition-System
/src/generateContent.py
649
3.59375
4
import pandas as pd import os # This file is to match the building id with an id in a csv file and return a name, description and wiki link # relevant to the building. class BuildingData(): def getData(self,predictionID): print(predictionID) dataset = pd.read_csv('Workbook1.csv', encoding= 'unicode_escape') ...
c893c609523d22aa44bebbe156113ef1b7fcf729
davidcinglis/cs-143
/network.py
16,916
3.5625
4
# This file contains all the classes and methods for the basic network architecture from events import * DATA_PACKET_SIZE = 1024 * 8 ACK_PACKET_SIZE = 64 * 8 TIMEOUT = 20 BIG = 10**20 class Network(object): """Network object for the simulation. This object contains dicts which keep track of all the nodes, links...
35752984c3f813399abe474dcee249f17b3dbb6c
mafdezmoreno/HackerRank_Callenges
/Practice/ProblemSolving/SparseArrays.py
734
3.625
4
#https://www.hackerrank.com/challenges/sparse-arrays/problem import math import os import random import re import sys # Complete the matchingStrings function below. def matchingStrings(strings, queries): recuento = [] #print(strings) #print(queries) for i in range(len(queries)): #recuento.appe...
b4131f154cbc2d62220d55c8b177e934d59a7cfa
mafdezmoreno/HackerRank_Callenges
/Practice/ProblemSolving/Node_at_head.py
1,318
3.953125
4
#!/bin/python3 # https://www.hackerrank.com/challenges/insert-a-node-at-the-head-of-a-linked-list/problem?h_r=next-challenge&h_v=zen&isFullScreen=true class SinglyLinkedListNode: def __init__(self, node_data): self.data = node_data self.next = None class SinglyLinkedList: def __init__(self): ...
40f2886dd9a9df5af1a7b579439924a38d006358
Mateuus/A3UndeadBRLife
/BEC/Plugin Examples/Function_Extensions/__init__.py
5,325
3.921875
4
class Function_Extensions(object): '''A Example Class to Extend some functions in Bec''' def __init__(self, instance): self.bec = instance self.mytext = "This is just an example text string!" ######################################################## ## Orginale functions we want to extend. Make a copy. ## ...
42b77c069625890a9c38ba595d2065b32b1fd09b
jgrimes91/cp1404practicals
/prac_01/loops.py
279
4.0625
4
for i in range (1, 21, 2): print(i, end=" ") print() for i in range (0, 100, 10): print(i, end=" ") print() for i in range (20, 0, -1): print(i, end=" ") print() stars = int(input("Enter number of stars: ")) for i in range (stars): n = i + 1 print("*" * n)
ccc04fabc35863c31fdb6f683f910a768d245d82
scottbing/SB_5410_Hwk131
/Hwk131/iris_classification/venv/iris_classification.py
6,061
3.625
4
from sklearn.datasets import load_iris from matplotlib import pyplot as plt from sklearn.linear_model import LinearRegression from statistics import mean import matplotlib.pyplot as plt import numpy as np from Perceptron import * import random def load_data(): iris = load_iris() # convert numpyarr to list ge...
98eff7c1eca1037699371f251ca50565da2a2739
helpmoeny/pythoncode
/Python_labs/lab06/lab06_stub.py
467
3.9375
4
def make_new_row(old_row): """Requires: -- list old_row that begins and ends with a 1 and has zero or more integers in between (has to have at least [1,1]) Returns: -- list beginning and ending with a 1 and each interior (non 1) integer is the sum of the corresponding old_r...
364bc17b6f406fb702e36dc19bb16411657def85
helpmoeny/pythoncode
/Python_projects/project10/currency.py
4,115
3.6875
4
import urllib.request class Currency( object ): def __init__(self,amount=0,currencycode=""): """Initialize an object of type Currency""" self.__amount = 0 self.__currencycode = "" #print(amount) #print the current amount in object #print(currencycode) #display if is...
75eea7ac650c7425843c23b8b107d987b2ca4e5e
helpmoeny/pythoncode
/Python_projects/project08/freecellStart.py
6,320
3.8125
4
import cards def setup(): """ paramaters: None (deck can be created within this function) returns: - a foundation (list of 4 empty lists) - cell (list of 4 empty lists) - a tableau (a list of 8 lists, the dealt cards) """ foundation = None # temporary value that needs to be replaced ...
51272948d3a64762b7abbb98bff568e9e86875ff
helpmoeny/pythoncode
/Python_projects/project11/proj11old.py
5,117
4.03125
4
import random import turtle import time from random import choice from random import randrange class Fishing(object): def Fish(): #creating multiple types of object fish types and returning one of them Fish = ['Whale Shark','Jack','Blacktip Shark','Tarpon','Roosterfish','Yellowfin Tuna','Peacock Ba...
0791a754b6620486dd07026672d3e27dd533da7f
helpmoeny/pythoncode
/Python_labs/lab09/warmup1.py
2,104
4.34375
4
## ## Demonstrate some of the operations of the Deck and Card classes ## import cards # Seed the random number generator to a specific value so every execution # of the program uses the same sequence of random numbers (for testing). import random random.seed( 25 ) # Create a deck of cards my_deck = cards.Deck() ...
19e67bca21d2cf81f91d6abb344154755d3b9ec3
helpmoeny/pythoncode
/other/binaryencoder.py
111
4.09375
4
temp=input("Enter text: ") newbinvalue="" for ch in temp: newbinvalue+=bin(ord(ch))[2:] print(newbinvalue)
309cca0dbdbadfb32981e1b5cd1585c0f48c9272
allandieguez/project_euler
/problems/problem_12/problem_solution.py
967
3.734375
4
from problems.problem_12.problem_statement import NUMBER_OF_DIVISORS from problems.utils import factorize divisor_map = {} def count_divisors(number): if number in divisor_map.keys(): return divisor_map[number] _, counter = factorize(number) if counter: div_count = counter[0] + 1 ...
ff8e77362c377f1c5787f0cf3ced3491c6f83065
MMuttalib1326/Binary-Heap
/BINARY HEAP.py
4,155
3.765625
4
# BINARY HEAP class Heap: def __init__(self,size): self.customList=(size+1)*[None] self.heapSize=0 self.maxsize=size+1 def peekofHeap(rootNode): if not rootNode: return else: return rootNode.custom[1] def sizeofHeap(rootNode): if not rootNode: ...
cba6f234a33e79c1153df6d8c5e1b6afca31b553
SophiaStellaMary/Guvi
/Find factorial of a number.py
126
4.0625
4
'''Factorial of a number''' fact=int(input()) factorial=1 for i in range(1,fact+1): factorial=factorial*i print(factorial)
baf7eb94b1f9502fa3fc51c24ca81b59aaf10660
SophiaStellaMary/Guvi
/Program to reverse every word in the string .py
134
3.984375
4
'''Hunter 11 Program to reverse every word in the string''' a=input().split() for i in range(0,len(a)): print(a[i][::-1],end=" ")
c6a3d3ed2b5f90ebcbfeeefef8237f9906e3f314
SophiaStellaMary/Guvi
/Player 3 print a number and reverse.py
62
3.8125
4
'''print a number and reverse''' a=input() a=a[::-1] print(a)
c2c1a711cfa510436b1ce96ca732a80b8fa890bf
SophiaStellaMary/Guvi
/Count the no.of.characters in string without counting the space .py
202
4.0625
4
''' Count the no.of.characters in string without counting the space ''' character = input() count = 0 for i in range(len(character)): if(character[i]==" "): continue count=count+1 print(count)
2a0c7647885523f0205e52e95220e1dca5fb4da2
SophiaStellaMary/Guvi
/calculate_the_power_of_a_number.py
110
3.734375
4
#calculate the power of a number N with given exponent(k) a,b=input().split() a=int(a) b=int(b) print(a**b)
a5816705dd924eee22232108936eb95840100f49
bakker4444/string_and_list_practice
/stringsandlists.py
581
3.96875
4
# Find and Replace words = "It's thanksgiving day. It's my birthday, too!" print words.find("day") print words.replace("day", "month") # Min and Max x = [2, 54, -2, 7, 12, 98] print min(x) print max(x) # First and Last x = ["hello", 2, 54, -2, 7, 12, 98, "world"] print "First value in array x is :", x[0] print "Last ...
b38cd4968d5754a2a3e26e2413c36f541a3f05c1
skyline75489/leetcode
/longest-common-prefix.py
426
3.515625
4
class Solution: # @return a string def longestCommonPrefix(self, strs): if len(strs) == 0: return '' first = strs[0] for i in range(0, len(first)): for s in strs[1:]: try: if s[i] != first[i]: return firs...
d8ab6c5a43c79d55ec807270e90209d899765034
ophd/HackerRankProblems
/Interview Prep Kit/Arrays/Minimum Swaps 2.py
660
4.09375
4
def minimumSwaps(arr): ''' Counts the minimum number of swaps required to sort an array. assumptions: n = len(arr) arr cotains all integers in interval [1, n] ''' arr = [a - 1 for a in arr] i = 0 swaps = 0 while i < len(arr) - 1: if arr[i] != i: j = arr[i] ...
a89c52ac3c7833fbefbba1f1db07837463b9eadb
ophd/HackerRankProblems
/Interview Prep Kit/Dictionaries and Hashmaps/Count Triplets.py
1,376
3.75
4
def countTriplets(arr, r): ''' Given an array of numbers and a common ratio, find the number of triplets following a geometric progression, such that arr[i] <= arr[j] <= arr[k], arr[j] = r * arr[i], arr[k] = r * r * arr[i] = r * arr[j] i < j < k. Note that, ...
5f489bb899465693b8cac6148798717290433fe6
ophd/HackerRankProblems
/SortingAlgorithms.py
2,921
3.578125
4
import time from functools import wraps def timed_func(fn, n=1000): @wraps(fn) def do_n_times(*args, **kwargs): time_start = time.perf_counter() for _ in range(n): result = fn(*args, **kwargs) time_elapsed = time.perf_counter() - time_start print(f'{fn.__name__}: {t...
95083c90b4cafcb776e2754c477f561a1f57544c
ophd/HackerRankProblems
/Python/Validating Postal Codes.py
436
3.84375
4
import re def validate_postal_code(postal_code): return bool(re.match(r'[1-9]\d{5}$', postal_code) and len(re.findall(r'(\d)(?=.\1)', postal_code)) < 2 ) if __name__ == "__main__": postal_codes = ['121426', '523563', '552523', '110000'] answers = [True, True, False, False] ...
93b57a19b934d732e35cab48950dfd4ba68a73d0
harvi7/Leetcode-Problems-Python
/Graph/course_schedule_ii.py
1,171
3.578125
4
# https://leetcode.com/problems/course-schedule-ii/discuss/59425/My-python-DFS-recursive-solution-(same-algorithm-for-207-and-210) class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: graph = [[] for i in range(numCourses)] visit = [0 for i in range(nu...
48f7e3f089d5f57920f6ecd7068ba0703b86eb0e
harvi7/Leetcode-Problems-Python
/Stack/remove_all_adjacent_duplicates_in_string.py
237
3.515625
4
class Solution: def removeDuplicates(self, S: str) -> str: sb = [] for ch in S: if sb and ch == sb[-1]: sb.pop() else: sb.append(ch) return ''.join(sb)
ced392f4c2e4436737e96392698a0335cbd36655
harvi7/Leetcode-Problems-Python
/Tree/maximum_depth_of_n-ary_tree.py
711
3.625
4
class Solution: def maxDepth(self, root: 'Node') -> int: # BFS Solution # queue, depth = [], 0 # if root: queue.append((root, 1)) # depth = 0 # for (node, level) in queue: # depth = level # queue += [(child, level+1) for child in node.children] ...
899382625dbbf83133ac3335eb7af6b5a8eed32e
harvi7/Leetcode-Problems-Python
/Heap/sort_characters_by_frequency.py
367
3.671875
4
class Solution: def frequencySort(self, s: str) -> str: char_map = {} for c in s: char_map[c] = char_map.get(c, 0) + 1 sorted_map = sorted(char_map, key = char_map.get, reverse = True) result = "" for count in sorted_map: result += ...
b8ab2035e439f95dad870724662495a6eae7c50c
harvi7/Leetcode-Problems-Python
/Design/implement_trie.py
1,445
4.0625
4
class TrieNode: isWord = False children = [] def __init__(self, val): self.val = val self.children = [None] * 26 self.isWord = False class Trie: def __init__(self): """ Initialize your data structure here. """ self.root = TrieNode("") def in...
deaff7e6f2a487fed95ebde53b182c140de9d334
harvi7/Leetcode-Problems-Python
/Two Pointers/backspace_string_compare.py
472
3.5
4
class Solution: def backspaceCompare(self, S: str, T: str) -> bool: new_s, new_t = [], [] for i in S: if i == '#': if new_s: new_s.pop() else: new_s.append(i) for j in T: if j ==...
55898d276abca50526eea76f250a8dca106e701d
harvi7/Leetcode-Problems-Python
/Hash Table/shortest_completing_word.py
611
3.53125
4
class Solution: def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str: def count(word): result = [0] * 26 for letter in word: result[ord(letter) - ord('a')] += 1 return result def dominates(c1, c2): return all(x2...
ed5145ae23fd3fc3fe3a974b6fd9bc6751421825
harvi7/Leetcode-Problems-Python
/Backtracking/increasing_subsequences.py
922
3.625
4
# https://leetcode.com/problems/increasing-subsequences/discuss/804364/Python-backtrack-with-Set class Solution: def findSubsequences(self, nums: List[int]) -> List[List[int]]: if not nums: return [] result = set() leng = len(nums) def backtrack(currArray, start...
b8983f7e35e7722b0744cc98e981109c1d9dfcc5
MikiEEE/SmallOS
/SmallPackage/SmallPID.py
1,332
3.578125
4
class SmallPID(): ''' @class smallPID() - Creates and keeps track of avialable Process ID's ''' def __init__(self, max=2**16): ''' @function __init__() - Initializes essential maintenence structures. @param max - int - The max number of process ID's. ...
aa46cbc941ed982725f2b8ff76e1dd93aa46e3d6
adam-suwei/python
/1 基础/4 变量.py
471
3.828125
4
x =10 x=x+10 print('x = ',x) # 变量交换是值传递 而不是地址传递 a = 'abc' b = a a = 'xyz' print('abc = ',b) print('xyz = ',a) #/除法计算结果是浮点数,即使是两个整数恰好整除,结果也是浮点数: a = 10/3 print(a) # //,%操作结果是整数 print(r'取商//\n:',10//3) print(r'取余数\%',10%3) f = 456.789 qqq = 123 #qqq is int [可变类型,类型可变] qqq = b'abc' #qqq is bytes print('qqq in by...
dd6b844f1c811bde00037305e1aee0c4adaff696
adam-suwei/python
/1 基础/8 list数据类型.py
4,209
3.75
4
# Python内置的一种数据类型是列表:list。list是一种有序的集合,可以随时添加和删除其中的元素。 #赋值 classmete = ['adam','peter','joy','judy'] classmete l = list('01234567') l = list(range(8)) # 不包括8 #获得长度 len(classmete) #4 #按索引取值 classmete[0] classmete[1] classmete[2] classmete[3] classmete[4] #oor # 取得最后一个元素 classmete = ['adam','peter','joy','judy']...
c75206afa72c2d8f89373f41a87367b57ea10728
adam-suwei/python
/1 基础/12 dict 数据结构 .py
4,494
3.71875
4
# dict 就是java中的map # # 构造推导式 a = dict(one=1, two=2, three=3) b = {'one': 1, 'two': 2, 'three': 3} c = dict(zip(['one', 'two', 'three'], [1, 2, 3])) d = dict([('two', 2), ('one', 1), ('three', 3)]) e = dict({'three': 3, 'one': 1, 'two': 2}) a == b == c == d == e #True d = {x: x**2 for x in (2, 4, 6)} d #{2: 4, ...
2d8476fd816fa5a24c0bff292c189124d14d3535
adam-suwei/python
/7 面向对象高级编程/4 定制类.py
3,015
3.953125
4
#---------------------------------------------------- # class 中的 __str__ class Student(object): def __init__(self,name): self.name = name def __str__(self): return ('hi~ I am a student ,my name is: %s' % self.name) __repr__ = __str__ s = Student('a gang') print(s) # hi~ I am a stude...
22bf42d158dd7ae6bbb6eea1ba7c1b3d462f4d9c
joonyi/ProjectEuler
/prob26.py
520
3.53125
4
""" 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle. Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part. """ # Unsolved a = 1 b = 7 digits = 8 for i in range(digits): n = a/b print(str(a)...
946fb66065cc14b9c0c3575ff728c65a398c8d95
joonyi/ProjectEuler
/prob30.py
827
3.796875
4
""" Digit fifth powers Problem 30 Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: 1634 = 1^4 + 6^4 + 3^4 + 4^4 8208 = 8^4 + 2^4 + 0^4 + 8^4 9474 = 9^4 + 4^4 + 7^4 + 4^4 As 1 = 1^4 is not a sum it is not included. The sum of these numbers is 1634 + 8208 + 9474...
244de02735c1b990fa273175475e8646c363dfef
kookou/python_machine_learning_study
/sba_api_01/contacts/calculator.py
667
3.6875
4
class Claculator: def__init__(self, num1, num2): self.num1 = num1 self.num2 = num2 def sum(self): return self.num1 + self.num2 def sub(self): return self.num1 = self.num2 def mul(self): return self.num1 * self.num2 def div(self): return self.num1 / sel...
63b59fa07c0e8df9f0cf9cb1bc76100a68b8ba7d
pulgamecanica/pw-python-03
/exercicio_1/analisa_ficheiro/acessorio.py
381
3.84375
4
import os def pede_nome(): while True: fileName = input("Please Enter the file name: "); if fileName.split(".")[-1] != "txt": print("The file should be a '.txt' file!") continue elif not os.path.exists(fileName): print(f"The file '{fileName}' doesn't exists") continue else: return fileName def g...
c946a796f2619483bba6b0593a3e3bd8295c7bc7
JeanCarlosSC/codigos-varios
/misPrimerosProgramas/python/range/src/range.py
195
4.03125
4
print("Printing current and previous number sum in a given range(10)") b=0 for i in range(10): if(i>0): b=i-1 c=i+b print("Current Number", i,"Previous Number", b, "Sum:", c)
c92b578655f3f0e82e090746691d2ba7d4472658
hwsonnn/python_crawling
/희원_python/0204___datetime.py
412
3.625
4
from datetime import date, time, datetime, timedelta #ctime = datetime.now() ctime = datetime.now() - timedelta(days=1) # - timedelta(days=1) 을 추가함으로써 어제 날짜 출력됨. print(ctime) print(type(ctime)) print(ctime.year) print(ctime.month) print(ctime.day) print(ctime.strftime('%Y%m%d')) ...
021d84be95ceabe759fe84c0d5eeee54056395dc
hwsonnn/python_crawling
/SQL/07(교수님)/03.py
718
3.75
4
data = 1234 print(type(data)) print("-"*20) #정수->문자열 data = str(data) print(type(data)) print("자리수:", len(data)) print("마지막:", data[-1]) print("-"*20) #문자열->바이트문자열 data = data.encode() print(type(data)) print(data) print("-"*20) #바이트문자열->decoding문자열 data = data.decode("utf-8") print(type(data)) ...
7b5004fcacaf06e8b5c292c8aa5f3394e0725b0a
hwsonnn/python_crawling
/희원_python/0204.py
1,599
3.5625
4
from urlToStr2 import urlToStr from bs4 import BeautifulSoup data = urlToStr('https://movie.daum.net/boxoffice/yearly?year=2019') import matplotlib.pyplot as plt #한글 폰트 사용 from matplotlib import font_manager, rc font_name = font_manager.FontProperties(fname="c:/Windows/Fonts/malgun.ttf").get_name() rc('font', fa...
331c75869fa0bd334a73dbdbd128d9207a14763b
hwsonnn/python_crawling
/희원_python/0205_datatype3.py
962
4
4
###### 파이썬 data type #딕셔너리(dictionary) : 키와 값의 쌍 dic = {'a' : 1, 'b' : 2, 'c' : 3} print(dic['a']) dic['d'] = 4 # list와 tuple과 달리 순서가 정해져있지 않으므로 # append 쓸 필요 없음. # 추가 dic['b'] = 4 # 수정 print(dic) print('-'*30) for item in dic : print(item, '=>', dic[item]) ...
9436d4c28c42a68726701aa2f5e0b498c0a761fe
hwsonnn/python_crawling
/pythoncrawling-master/07/02_file3.py
245
3.59375
4
def fileToStr(filename) : #파일 열기 f = open(filename, "r", encoding="utf-8") data = f.read() #파일 종료 f.close() return data fname = input("파일명을 입력하세요.") data = fileToStr(fname) print(data)
3aad29f567bca81931caf96fab54c14b262da6bb
SilasPillsbury/Othello
/Othello.py
952
3.65625
4
b =[[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 2, 0, 0, 0], [0, 0, 0, 2, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] def play(b): 'Things' return None def check_playable(player,location,b...
6d510ee1145d9bf01432ae267104cb9c6fd59e33
sraj50/plexus-challange
/app/Overflow.py
1,749
3.734375
4
from collections import deque from .Glass import Glass def find_glass(i: int = 0, j: int = 0, k: float = 0) -> float: glass = Glass() glass.fill(k) if j > i: raise Exception(f"j cannot be greater than i for index (i={i}, j={j})") index_map: dict = map_index(glass) node = index_map.get((i...
0bb02c4ac61dd820912a0326d626da24ebb05442
GaryGky/Machine-Learning
/Kanada-Project/DeepCNN.py
2,235
3.71875
4
# Author By Gary1111 import numpy as np import pandas as pd from keras import Sequential from keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense train = pd.read_csv("data/DataPre/train_XY.csv", index_col=False) test = pd.read_csv('data/DataPre/test.csv', index_col=False) test.rename(columns={"Unnamed: ...
b41cccdba55a6a96a52e23b9943ac87748d05842
ChoiHeon/algorithm
/02_백준/[11866] 요세푸스 문제 0.py
345
3.53125
4
# https://www.acmicpc.net/problem/11866 """ """ from collections import deque N, K = map(int, input().split()) queue = deque() for i in range(1, N+1): queue.append(i) answer = [] while queue: for _ in range(K-1): queue.append(queue.popleft()) answer.append(str(queue.popleft())) print('<' + ...
4ec7c34c857e4c9281d07edb44e3a0db34190ff3
ChoiHeon/algorithm
/04_2020 카카오 신입 개발자 블라인드 채용 1차 코딩 테스트/04_가사 검색 (효율성 100% 통과).py
2,041
3.5
4
# https://programmers.co.kr/learn/courses/30/lessons/60060 """ 효울성 100% 통과를 하기 위해 trie 자료구조를 사용 query 를 Trie 에 저장할 경우 효율이 떨어지므로 (bfs 탐색을 해야 하므로) word 를 저장 * query 의 길이 - Trie 객체를 원소로 가지는 리스트를 생성 - word 의 길이를 인덱스로 하는 Trie 객체에 삽입 - query 의 길이를 인덱스로 하는 Trie 객체에서 해를 찾음 * 추가 가능 조건 - query 의 중복이 가능 - d...
e461619064c1baef78415057db2e4f7310c5efb1
danwspark/CDClabcode
/Queues.py
4,727
3.953125
4
######################################## # CS63: Artificial Intelligence, Lab 1 # Spring 2016, Swarthmore College ######################################## class _Queue(object): """Abstract base class for FIFO_Queue, LIFO_QUEUE, and Random_Queue A queue supports the following operations: - adding items ...
c0633c04c4d4a4b41dcbeccfabce2f0519724fa2
63070086/Pyhon
/21.2D Distance.py
316
3.6875
4
"""def""" def numsum(): """docstring input""" numx1 = float(input()) numy1 = float(input()) numx2 = float(input()) numy2 = float(input()) sum1 = (numx2-numx1)**2 sum2 = (numy2-numy1)**2 sum3 = sum1+sum2 sum4 = sum3**0.5 print("Distance = %0.03f"%(sum4)) numsum()
46e11ec8a1465890010c9c713677fcdf921c5a21
63070086/Pyhon
/22Hexagonal Prism.py
260
3.59375
4
"""Describe""" def sumsum(): """ input""" rong = float(input()) height = float(input()) square = (rong*height)*6 sum1 = (((((3**0.5)/4)*rong**2)*6)*2) sum2 = ((square+sum1)/10000) print("%0.02f squaremetre"%sum2) sumsum()
12ea9a0481d9fbf063445061ff41d822d55673d1
63070086/Pyhon
/28Caplock crisis.py
143
3.515625
4
"""abc""" def abc(): """Lower Translate""" upper = input() uplow = ord(upper) low = uplow+32 print(chr(low)) abc()
866b452a25cf61d858f06885874e58a36de6f603
63070086/Pyhon
/9Escape Sequence II.py
398
3.6875
4
"""input name""" def numbername(): """input""" name1 = input() name2 = input() name3 = input() name4 = input() name5 = input() name6 = input() name7 = input() name8 = input() name9 = input() print("%s\t%s\t%s"%(name1, name2, name3)) print("%s\t%s\t%s"%(name4,...
076aaca238675218bbd2c8c9458d3d0368865934
63070086/Pyhon
/24how long.py
173
3.65625
4
"""tran""" def tran(): """input int""" num = int(input()) numabs = abs(num) num1 = str(numabs) num3 = len(num1) print("%d"%(num3)) tran()
3dc997bdf2f3bf1628e164c8061ab3da003f7575
63070086/Pyhon
/46binary number2.py
186
3.578125
4
"""string""" def main(): """input func""" bi_num1 = int(input(), 2) bi_num2 = int(input(), 2) bi_num3 = int(input(), 2) print(bi_num1*bi_num2*bi_num3) main()
3c080adc19961c9138b7604b89503fee237b88d8
63070086/Pyhon
/60should be chosen.py
1,215
3.640625
4
"""funtion""" def suba(num): """funtion""" if num >= 1 and num < 4: num2 = num * 725 return num2 elif num >= 4 and num % 4 == 0: num1 = num/4 num1 = round(num1) num2 = (num1*(725*3)) return num2 elif num >= 4 and num % 4 != 0: num1 = nu...
98f50aea08160eed4430d8490e73338b8009620c
justin-ht-dang/competitiveProg
/ICPCprep/ANZACbeginner/arithmetic.py
346
3.90625
4
two_num =input() num_pair = two_num.split() num1 = int(num_pair[0]) num2 = int(num_pair[1]) print(str(num1) + " * " + str(num2) + " = " + str(num1*num2)) if(num2 != 0): print(str(num1) + " / " + str(num2) + " = " + str(num1//num2) + " remainder " + str(num1%num2)) else: print(str(num1) + " / " + str(num2) + " ...
4d787bf1a4ee7d96216520ffa9331a8a1ad670a0
nickconway/connect-four
/imports.py
5,995
4.1875
4
import random # Player marks BLANK = "_" PLAYER1 = "X" PLAYER2 = "O" # Column constants MIN_VALUE = 5 MIN_COLUMN = 1 # Input constants NO = "n" YES = "y" # prints out the current board # Input: board # Output: None def printBoard(board): for row in board: row_ = 0 count = 0 for col in r...
1f2a54b15cf94c8e841df8de7d9f7b2ec53bbaca
oxygenum44/zpi
/naming.py
6,879
3.59375
4
import operator import features import copy import tweet_cleaner def assign_names(cleaned_tweets_clusters, method="two_most_frequent"): """ Function assigning names to clusters by a given method :param cleaned_tweets_clusters: List of tweets` clusters (list of lists of lists of words) :param method: N...
94116c21a5799d62dee008a79229a30a598386b9
adevesa/trucopython
/truco/NaipesEspanioles.py
3,815
3.5625
4
## Naipes Espanioles funciones. from itertools import product, permutations import random ''' @@Name: crear_baraja @@Parm: none @@Desc: Crea los 50 naipes españoles, 12 de cada palo y los 2 comodines. Los Naipes estan constituido en una tupla (PALO, NUMERO) La...
2a5d3eb589bb0c4591382bf90700987406ff372d
julia-ediamond/python
/recap.py
728
4.34375
4
fruits = ["banana", "apple", "cherry"] print(fruits[-1]) fruits.append("pineapple") print(fruits) fruits.pop(0) print(fruits) digits = [1, 2, 3] decimal = [1, 2, 3] nested = [[1, 2, 3], ["hello"]] for item in fruits: print(item) for item in nested: print(item) for i in item: print(i) people = [ ...
e1a073464ac2c434d9d4c6ea314ab7422beaac06
julia-ediamond/python
/dictionaries/dict_ex3.py
468
3.53125
4
names = ["Bel", "Elnaz", "Gia", "Izzy", "Joy", "Katie", "Maddie", "Tash", "Nic", "Rachael", "Bec", "Bec", "Tabitha", "Teagen", "Viv", "Anna", "Catherine", "Catherine", "Debby", "Gab", "Megan", "Michelle", "Nic", "Roxy", "Samara", "Sasha", "Sophie", "Teagen", "Viv"] #names_dict = {}.fromkeys(names, "unkown") # ...
f53e3e87ff1962e04b4eec9633b780087bdb1482
julia-ediamond/python
/loops/for_exer.py
127
3.859375
4
# Q2 start_number = int(input("Enter a number: ")) sum_ = 0 for i in range(0, start_number + 1): sum_ += i print(sum_)
cf652ca875116897caa6431822093f1bd361e6d3
julia-ediamond/python
/data/process_employee_birthday.py
472
3.609375
4
import csv with open('data\data1\employee_birthday.csv', mode="r") as csv_file: csv_reader = csv.DictReader(csv_file, delimiter=",") line_count = 0 for row in csv_reader: if line_count == 0: print(f'Column names are {", ".join(row)}') print( f'\t{row["name"]} works ...
d899282f97173cc5aa3af6bba09934a2a43a8a95
lucpena/Stonks.py
/stonks.py
3,297
3.53125
4
import math import numpy as np import pandas as pd import pandas_datareader as web from sklearn.preprocessing import MinMaxScaler from keras.models import Sequential from keras.layers import Dense, LSTM import matplotlib.pyplot as plt plt.style.use("fivethirtyeight") # Getting the DataFrame with the stock qu...
6fe3950c7987a7485c2565c2477d84c677a8eb9c
StevenCThaller/March20PythonAlgos
/validbraces.py
1,376
4.0625
4
from stacks import * def ValidBraces(string): # set of opening and closing braces for easy checking openings = [ "(", "[", "{" ] closings = [ ")", "]", "}" ] # dictionary of opening braces and their corresponding closing braces valids = { "(": ")", "{": "}", "[": "]" } ...
38e477dfea4d52fec96a70aeb69df0d0a32fcf3b
saequus/learn-python-favorites
/Tasks/InterestingStr.py
684
3.734375
4
# https://leetcode.com/discuss/interview-question/350312/google-onsite-interesting-string from functools import lru_cache def interesting_string(s): @lru_cache(maxsize=len(s)) def dfs(i): if i == len(s): return True j = i while j < len(s) and s[j].isdigit(): k...
9cd88a850ddd8efceeff3721b6a39eedef99e9d3
saequus/learn-python-favorites
/Tasks/24_SwapPairs.py
6,218
3.9375
4
# class Node: # def __init__(self, val): # self.val = val # self.next = None # # def traverse(self): # node = self # while node: # print(node.val) # node = node.next # # class SpecialList: # def __init__(self): # self.head = Node # # def li...