blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
5b2a21644cbed79b9f35726956dfe6c86c96dcba
rshinoha/DSAWork
/Chapter01/P1.32-simple_calculator.py
2,221
4.34375
4
# Data Structures and Algorithms in Python Ch.1 (Goodrich et. al.) # Project exercise P1.32 # Ryoh Shinohara # ======================================================================================= # Write a Python program that can simulate a simple calculator, using the console as the # exclusive input and output dev...
72b8f08673c8e52f9ea8c533ff5a721ad5a38b23
jedzej/tietopythontraining-basic
/students/stachowska_agata/lesson_02_flow_control/adding_factorials.py
159
3.796875
4
n = int(input()) sum_of_factorials = 0 factorial = 1 for i in range(1, n + 1): factorial *= i sum_of_factorials += factorial print(sum_of_factorials)
a17fc3ede367fd345a6011d47bd0eca35a48ea1b
MrHamdulay/csc3-capstone
/examples/data/Assignment_5/gvnpri022/question1.py
1,214
3.890625
4
"""question 1- assignment 5 prinesan govender 14 april 2014""" choice="" msg="" #initialise variables while(choice!="X"): print("Welcome to UCT BBS") print("MENU") print("(E)nter a message") print("(V)iew message") print("(L)ist files") print("(D)isplay file") print("e(X)it") ...
7c668d1430781155ce42907fef3580c4924d0724
tarak2014/pytest
/test_cases.py
557
4.125
4
from basicmath import util def test_add_num(): """Test is to Addition of two numbers, and return the output value""" assert util.add_num(3,4) == 7 def test_sub_num(): """Test is to Substraction of two numbers, and return the output value""" assert util.sub_num(3,4) == -1 def test_mul_num(): """Te...
2f348b7d4a765d145ad225dc0f32de0f4f091180
PaulSayantan/problem-solving
/LEETCODE/Easy/Two Sum/twosum.py
372
3.59375
4
from typing import List def twoSum(nums: List[int], target: int) -> List[int]: index = dict() for i , n in enumerate(nums): if target - n in index: return [index[target - n], i] index[n] = i return [] if __name__ == "__main__": nums = [int(x) for x in input().split()] t...
905f4234af49a86b33cf4342a63c7d20c0366dc2
gcakir/2017_AaDS
/HW3/1/guess.py
460
3.671875
4
import random def createList(n): lst = list() for i in range(1, n): lst.append(i) return lst def binary_search(A, n, x): p = 0; r = n while p <= r: q = int((p+r)/2) # print(A[p:r+1]) if A[q] == x: return q elif A[q] != x and A[q] > x: r = q - 1 elif A[q] != x and A[q] < x: p = q + 1 return...
cfbdd781e949bc05b05196e275a02f0f6da47d59
Kaiquenakao/Python
/Estruturas de repetição em Python/Exercicio14.py
469
3.890625
4
""" 14. Faça um programa que leia um número inteiro positivo par N e imprima todos os números pares de 0 até N em ordem decrescente """ try: N = int(input('Insira um número positivo inteiro par: ')) if (N > 0) and (N % 2 == 0): for i in range(N, -1, -2): print(i, end=' ') else:...
94fc2a8a79adc3f35c4b291091ad0bce0e9a0c77
wmboult94/NLP
/Workshops/Topic 0/solutions/print_word_counts.py
594
3.875
4
# coding: utf-8 def print_word_counts(filepath): input_file_path = filepath input_file = open(input_file_path) input_text = input_file.read() word_counts = collections.defaultdict(int) for word in input_text.split(): word_counts[word] += 1 for word, count in word_counts.items(): ...
fb7779f71755c75a0dbf8ae1313d5dd09c07b4e8
IIITSERC/SSAD_2015_A3_Group2_35
/w.py
4,184
3.671875
4
import random class board: def __init__(self): #creates a rectangle of walls stored in an array self.bord=[] self.data=[]; for i in range(30): self.f=[] for j in range(80): self.f.append(" ") self.bord.append(self.f) for i in range(30): self.bord[i][0]='X' self.bord[i][79]='X' for i in ra...
9afefd63cd39a3c32471ed4edd318b01505e1104
hemincong/MachineLearningExercise
/utils/file_utils.py
735
3.71875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def read_csv(file_name): m = [] with open(file_name, "r") as infile: for line in infile: pos = line.strip().split(',') tmp = list(map(float, pos)) m.append(tmp) return m def read_csv_split_last_col(file_name): ...
59fc3900383a06c8c925050535a78476cb28d3f1
evilnsm/learn-python
/Project Euler/049.py
988
3.640625
4
#coding:utf-8 ''' 公差为3330的三项等差序列1487、4817、8147在两个方面非常特别:其一,每一项都是素数;其二,两两都是重新排列的关系。 一位素数、两位素数和三位素数都无法构成满足这些性质的数列,但存在另一个由四位素数构成的递增序列也满足这些性质。 将这个数列的三项连接起来得到的12位数是多少? ''' from math import sqrt def is_p(n): if n== 1: return False elif n == 2: return True else: for i in xrange(2,int(sqr...
abb09ed86c1601ee663fbc3574c41a8a76f195e5
Oleksandr015/Python-podstawy
/Day_5.1/inheritance.py
1,339
4
4
class A: def __init__(self, a): self.a = a def square_value(self, value): return value ** 2 class B(A): def __init__(self, a, b): super().__init__(a) self.b = b class Animal: def __init__(self, name, age): self.name = name self.age = age def intr...
3f9df82b5f9c8e5c66ccfac0d30e0175e2ab01c7
thejohnjensen/code-katas
/src/test_sum_terms.py
402
3.5625
4
"""Module to test sum of nth term module.""" import pytest nth_term = [ (1, '1.00'), (0, '0.00'), (2, '1.25'), (3, '1.39'), (59, '2.40'), (9, '1.77'), (5, '1.57'), (99, '2.58') ] @pytest.mark.parametrize('n, result', nth_term) def test_series_sum(n, result): """Test the fuction series sum for nth term."...
4536bd8802cef5561fb1b16d05eb10a9968c9b82
sornaami/luminarproject
/objectorientedprogramming/bankapplication.py
1,066
4
4
import datetime class Person: def setPerson(self,name,age): self.name=name self.age=age def printPerson(self): print(self.name,",",self.age) class Bank(Person): bank_name="Sbk" def createAccount(self,acno): self.acno=acno self.balance=3000 def deposit(self,amo...
76808eb3ef8c480fe75943cc5a902d14ae2fefdc
jianwenyu/CPP
/python/29_formatMethods.py
927
3.765625
4
defaultOrder = "{},{},{}".format('lee','john','tom') print(defaultOrder) positionalOrder = "{1},{2},{0}".format('lee','john','tom') print(positionalOrder) keywordOrder = "{s},{b},{n}".format(b='lee',s='john',n='tom') print(keywordOrder) print("Binary representation of {0} is {0:b}".format(12)) print("Octal...
ba8cb0b2acaabe87e809df516f159a3fc3d1bdab
cameronbrown/hello-ci
/hello/util.py
367
3.515625
4
"""Fake utilitites for testing testing""" def add_two(num): """Add two to num""" return num + 2 def add_three(num): """Add three to num""" return num + 3 def add_four(num): """Add four to num""" return num + 4 def add_five(num): """Add five to num""" num += 1 num += 1 num...
244b3b8af83274c8da643d4c9b4639c4919cb247
ThomasTheDane/datasci_course_materials
/assignment3/wordcount.py
2,255
3.71875
4
import MapReduce import sys import json """ Word Count Example in the Simple Python MapReduce Framework """ mr = MapReduce.MapReduce() # ============================= # Do not modify above this line # def mapper(record): # # key: document identifier # # value: document contents # key = record[0] # v...
c92dfe94b9df589f6bb44a9c86112bd507736fd6
hochan222/vs-code-test
/python/BJ_10039.py
162
3.546875
4
total = [] for _ in range(5): score = int(input()) if score < 40: total.append(40) else: total.append(score) print(int(sum(total)/5))
1785b26b010d448c5dce0e53337ff7988816c2df
vyxxr/python3-curso-em-video
/Mundo3/099.py
579
4.21875
4
''' Faça um programa que tenha uma função chamada maior(), que receba vários parâmetros com valores inteiros. Seu programa tem que analisar todos os valores e dizer qual deles é o maior. ''' from time import sleep def maior(* num): print('-=' * 30) print('Analisando os valores informados...') for c in num...
153cb0d6624bdccbdedc39e675958b3ee0f415a6
qleoz/snake-learning
/smart_ai.py
2,200
3.6875
4
import snake as s import random import sys import math as m choices = ['l', 'r', 'f'] board = [] snake = [] direction = '' #returns location of food, None if no food def findfood(): global board, snake, direction for i in range(len(board)): for j in range(len(board[i])): if(board[i][j] == ...
e5000be46058acf6390ddb8275207b625509259e
zhangzongyan/python0702
/day12/obj4.py
647
3.8125
4
import obj1 class Test: def __init__(self): super().__init__() # 父类是object class Student(obj1.Person): def __init__(self, name, age, no, school_tm): # 调用父类obj1.Person的__init__方法,构建name和age属性 # obj1.Person.__init__(self, name, age) # super(Student, self).__init__(name, age) super().__init__(name, age) s...
600f34e6b0c35240803a85147416f84e394f9f23
adolgert/cascade
/src/cascade/input_data/db/data_iterator.py
608
4.15625
4
def grouped_by_count(identifiers, count): """ Given a list, iterates over that list in sets of size count. The last set will be of size less than or equal to count. Args: identifiers (List): Can be any iterable. count (int): Number of items to return on each iteration. Returns: ...
1c9aeea69b0068d3bbc9245ec004c0aebb631d7c
Omkar02/FAANG
/RemoveDupFromSortedArray.py
1,264
3.890625
4
import __main__ as main from Helper.TimerLogger import CodeTimeLogging fileName = main.__file__ fileName = fileName.split('\\')[-1] CodeTimeLogging(Flag='F', filename=fileName, Tag='Array') ''' Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. ...
d30157b9c5f4fc1d6c6c6ec28a270335f19ad5fb
phallusferrus/phallusferrus.github.io
/blogs/works/python/ttt.py
4,727
3.859375
4
import random #import time ###I want the computer to anticipate victory and act on it ###if b_r_1[0] == b_r_1[2] and "2" in a_m: ### move = 2 ###should be roughly 16 different emminent victory conditions twice as many victory conditions...weird math dude... b_r_1 = ["1", "2", "3"] b_r_2 = ["4", "5", "6"] b_r_...
dad5265b51ef8511575ccc70f5819c276f386bbc
Saurabh-12/Python_Learning
/QueueExamplePython.py
477
3.6875
4
from collections import deque class Queue: def __init__(self, max_size = 10): self._queue = deque(maxlen = max_size) def is_empty(self): return self._queue == [] def enqueue(self, data): self._queue.append(data) def dequeue(self): return self._queue.popleft() q...
48684ade4b7e161c2fa7b222bc1b3c23a49b73f7
xpdAcq/rapidz
/rapidz/orderedweakset.py
1,236
3.578125
4
# -*- coding: utf8 -*- # This is a copy from Stack Overflow # https://stackoverflow.com/questions/7828444/indexable-weak-ordered-set-in-python # Asked by Neil G https://stackoverflow.com/users/99989/neil-g # Answered/edited by https://stackoverflow.com/users/1001643/raymond-hettinger import collections.abc import...
fd4baecf9b9df4e055ccad8e86d36ef6caca1695
JasonXJ/algorithms
/leetcode/lc56.py
778
3.578125
4
class Solution(object): def merge(self, intervals): if len(intervals) == 0: return intervals intervals.sort(key=lambda x:x.start) merged = [intervals[0]] head = merged[0] for x in intervals[1:]: if x.start > head.end: # New interval me...
9679aa489481d024695991ca7ee7877da58fd2b5
mhoogs/test
/practice midterm.py
448
3.921875
4
def remove_bracket(sentence): count = 0 for i in sentence: if i =="(": left_bracket = count elif i == ")": right_bracket = count count = count + 1 new_sentence= sentence[0:left_bracket] +sentence[right_bracket+1:len(sentence)]...
6dbd2508b1746384c9e4e2a9f313672ebcd8822e
Luzhnuy/katerina_labs
/double_letter.py
74
3.859375
4
word = input("Type a word: ") for el in word: print( el + el, end="")
615e12717cb54f15eae7251b7c52e563cf53712d
sunshot/LeetCode
/480. Sliding Window Median/solution1.py
792
3.9375
4
from typing import List class Solution: def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]: left = 0 right = left + k result = [] while right <= len(nums): temp = sorted(nums[left:right]) if len(temp) % 2 == 0: index = len(te...
07cea477966a51de75c9adf51e6e6f16987a0b37
paulross/pprune-calc
/AN-24_Nizhneangarsk/cmn/polynomial.py
2,569
4.15625
4
import typing def polynomial(x: float, *args: typing.List[float]) -> float: """Returns the evaluation of the polynomial factors for the value x.""" ret = 0.0 for i in range(-1, -len(args) - 1, -1): ret += args[i] if i == -len(args): break ret *= x return ret def p...
7d3435373245c23229b485902db816bcff049aa4
angiereyes99/coding-interview-practice
/easy-problems/SubtracttheProductandSumofDigitsofanInteger.py
1,805
4
4
# PROBLEM: # Given an integer number n, return the # difference between the product of its # digits and the sum of its digits. # EXAMPLE: # Input: n = 234 # Output: 15 # Explanation: # Product of digits = 2 * 3 * 4 = 24 # Sum of digits = 2 + 3 + 4 = 9 # Result = 24 - 9 = 15 from typing import List class Solut...
b78a81ba2ed1f0a512f4a6caebafa33eddd74249
Lucas-Moura-Da-Silva/UNIFESP-aulas-optativas-de-Python
/Exercícios/Exercícios_aula2_11-05_até_17-05/Ex002.py
776
4.15625
4
'''2) Crie uma rotina que solicite uma frase ao usuário e retorne o número de caracteres na frase e o número de espaços.''' #cores cores = {'limpa':'\033[m', 'branco':'\033[1;30m', 'vermelho':'\033[1;31m', 'verde':'\033[1;32m', 'amarelo':'\033[1;33m', 'azul':'\033[1;34m', ...
4176b1afd8ec9a05b41ffb6a8204bd09769276cb
Vladislav124382423/Study
/44.py
278
3.90625
4
x = int(input("enter number")) y = int(input("enter number")) z = int(input("enter number")) if x and y and z < 1: if (x < y) and (y < z): x = (y + z)// 2 print(x) if (y < x) and (y < z): y = (x + z)// 2 print(y) else: z = (x + y)//2 print(z)
4f82110ce9eb8704353c792e806ca40112e955a1
xzpjerry/learning
/python/playground/searching/dfs.py
555
3.890625
4
from tree import Node, tree class dfs_tree(tree): def dfs(self, target): visited, stack = [], [self.root] while stack: node = stack.pop() print(node.value) if node.value == target: return True visited.append(node) stack....
3b6fce219985223c83c1e632d3b16b8ead590f60
Timothy2015/Leetcode
/String/5.最长回文子串.py
1,927
3.625
4
# https://leetcode-cn.com/problems/longest-palindromic-substring/ class Solution: def longestPalindrome(self, s: str) -> str: # 思路:先找到每一个回文子串,再比较每个子串长度,返回最长回文子串 # 双指针:从中心开始,向两边扩展,寻找回文子串 # 自定义切片slice函数 -- 浦发机考python不能直接使用切片 def slice(str, i, j): res = '' ...
83e27022def1ef851f1bf93159f5235a1477b244
VaishnaviReddyGuddeti/Python_programs
/Python_Tuples/TupleLength.py
172
4.21875
4
# To determine how many items a tuple has, use the len() method: # Print the number of items in the tuple: thistuple = ("apple", "banana", "cherry") print(len(thistuple))
cf69d61426156b42ee7916c2585b73057ffe92e4
GeorgeTheTypist/LearnPythonPR
/Functions.py
4,635
4.3125
4
__author__ = 'Pneumatic' def printme(parameters): # create a function called printme using def """This is a doc sting document what this function will do. This prints a passed string into this function""" print(parameters) # prints anything that is stored inside parameters return printme("I'm first cal...
2b3e065bd4d11950d5b53a66c3c9631590d8a38c
wulujunwlj/front-end-learning
/python/python-tutorial/functional-program.py
2,553
3.5625
4
# Functional Programming import functools def add(x, y, f): return f(x) + f(y) def func(x): return x * (x + 1) print add(-5, 6, abs) print add(-5, 6, func) def f(x): return x * x print map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9]) def add(x, y): return x + y print reduce(add, [1, 4, 6, 7, 8]) print sum([1, 4, 6, 7, 8]...
e7c1309e18ea0a4bb3bdb2bb1faae800bf8c0b01
hallgrimur1471/algorithms_and_data_structures
/junkyard/c3_5_sort_stack.py
760
4.1875
4
#!/usr/bin/env python3.5 """ Write a program to sort a stack such that the smallest items are on the top. You can use an additional temporary stack, but you may not copy the elements into any other data structure (such as an array). The stack supports the following operations: push, pop, peek, and isEmpty. """ def s...
3cf7d5e752e6cee87333b366260c9653e22e9a66
screx/rosalind_solutions
/ham_distance.py
241
3.5625
4
def ham(dna1, dna2): l = len(dna1) distance = 0 for i in range(l): if dna1[i] != dna2[i]: distance += 1 return distance def solution(txt): f = open(txt) dna1 = f.readline() dna2 = f.readline() f.close() return ham(dna1, dna2)
aa9c8138570085226a5a372e2aeb17d70e6f1c78
fanhexiaoseng/Project-practice
/知识点/code/线性查找.py
278
3.734375
4
# _*_ coding : utf-8 _*_ def search(arr, n, x): for i in range(n): if arr[i] == x: return i return -1 arr = ['A', 'B', 'C', 'D', 'E'] x = 'D' realut = search(arr, len(arr), x) if realut != -1: print(realut) else: print("不存在!") #3
d5b59ff5725bc969689af8de9d5fcea0e6d0d547
theopolis/osquery
/tools/codegen/substitute.py
1,314
3.609375
4
#!/usr/bin/env python3 # Copyright (c) 2014-present, Facebook, Inc. # All rights reserved. # # This source code is licensed in accordance with the terms specified in # the LICENSE file found in the root directory of this source tree. """ Replace every occurrences of pattern in every string of input file and write...
1040e773bb8f115e2988b2b379893721118c8e4a
katatohuk/python
/python_work/players.py
176
3.71875
4
players = ['Igor', 'Masha', 'Petro', 'Vasya', 'Gena'] print(players[0:3]) print("Here are 3 first players of my dream-team:") for player in players[:3]: print(player.title())
7d40a8e758afcb95a4a7d2d79e5657f43d58eb65
ArchitKumar1/Competitive_Programming
/algs/a.py
210
3.546875
4
n = int(input()) for i in range(1,n+1): s = str(n) cnt = 0 while(len(s)!=1): temp = 1 for i in s: temp *= int(i) s = str(temp) cnt+=1 print(n," ",cnt)
6f72f7bde6149bd82066c6d4eb67a0882bfc1eab
Darrenrodricks/w3resourceBasicPython1
/w3schoolPractice/intdiff.py
382
4.09375
4
# Write a Python program which will return true if the two given integer values are equal or their sum or difference is 5. def test_number5(x, y): if x == y or abs(x - y) == 5 or (x + y) == 5: return True else: return False print(test_number5(7, 2)) print(test_number5(3, 2)) print(test_number5...
5b70934f7f7f432ee767039a11760219ffaa2353
sphilmoon/coreyschafer
/basic/02_strings.py
688
4.375
4
message = 'Hello Phil\'s World' print (len(message)) # print out the number of length or character. print(message[0:14]) # this is called 'Slicing'. # Method and function. method is a function that belongs to an object. print(message.find('World')) # find the and argument. message = message.replace('World', 'Unive...
3a926be93f5fb50af5f6fa053cc6788a56887ca1
samysellami/Face-recognition_ComputerVision
/solution.py
5,079
3.6875
4
def face_rec(image): """function that recognizes the person in the given photo input: image grayscale or color image with face on it output; person_id: id of a person (class) """ from matplotlib import pyplot as plt import numpy as np import cv2 from collections import Counte...
c4f6b5025f251b5f195dd50434dfd7b74f4b53b6
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/leap/7c0304694e024bd1ae3362008867ecf6.py
215
3.734375
4
def is_leap_year(year): try: if (year%4==0 and year%100!=0) or year%400==0: return True else: return False except TypeError: return False
538a3a365119431ec35f657a1407989df860b3aa
MarvinSilcGit/Alg
/Python/2018-2019/Quadrado.py
532
4.03125
4
cont = 1 while cont != 0: print() a = input("Digite a lado de um quadrado: ") if a.isdigit() == True: a = int(a) z = 0 y = 0 w = 0 while y != a: while z != a: z += 1 while w != 1: ...
c102603ebf4673c8dd6f1fb9c28d7cc98605a09e
lincolnjohnny/py4e
/2_Python_Data_Structures/Week_6/example_08.py
251
3.90625
4
# Sorting Lists of Tuples d = {'a': 10, 'b': 1, 'c': 22} # declaring a dictionary with keys and values print(d.items()) # dict_items([('a', 10), ('b', 1), ('c', 22)]) print(sorted(d.items())) # [('a', 10), ('b', 1), ('c', 22)]
b8f4ad4ce604083791daf84984b9d3563b7ef64a
DilyanTsenkov/SoftUni-Software-Engineering
/Python Fundamentals/03 Lists Basics/Exercises/10_Bread_Factory.py
1,200
3.53125
4
day_events = input().split("|") new_day_events_list = [] energy = 100 coins = 100 close = False for i in day_events: new_day_events_list.append(i.split("-")) for i in range(len(new_day_events_list)): event = new_day_events_list[i][0] number = int(new_day_events_list[i][1]) if event == "r...
49da829aa548a405955939f1342e2356811bc238
Blasco-android/Curso-Python
/desafio99.py
745
4.3125
4
''' Exercício Python 099: Faça um programa que tenha uma função chamada maior(), que receba vários parâmetros com valores inteiros. Seu programa tem que analisar todos os valores e dizer qual deles é o maior. ''' from time import sleep def linha(): print('=-' * 30) def maior(* num): print('Analisando os valo...
a4c89103de6d9f847d601b9e238a6fa7aa56382b
rd37011/ml
/kmeans/kmeans.py
3,712
3.65625
4
#!/usr/bin/env python import csv import random import numpy as np import math """kmeans.py: K-Means clustering algorithm.""" __author__ = "Ryan Diaz" __copyright_ = "Copyright 2018, University of Miami, Coral Gables, FL " class _kmeans_: def __init__(self, p, label): self.point = p self.label =...
4600cebeebba19779f4825459e18278763094e5c
beatonma/snommoc
/util/cleanup/unused.py
1,167
3.765625
4
""" When inspecting code we may find classes or functions that are not currently in use but we do not want to delete them as they may be useful later. Such classes should be updated to inherit UnusedClass, and such functions should be marked with the @unused decorator. This allows """ class UnusedException(BaseExcept...
892f9108ac5118fe346a440e42e592dc3f1bf8c4
cah835/Intro-to-Programming-1284
/Classwork Programs/classwork.py
461
3.78125
4
def main(): my_list = [1,2,3,4,5,6,7,8,9,10] total = sum(my_list) for each_element in range(11): print(each_element) print(total) total2 = 0 for element in my_list: total2 += element print(total2) total3=0 index =0 while index < len(my_list): total3 += m...
f646d10e0c1b8102b04ac91920290900ae0792aa
paulohenriquegama/Blue_Modulo1-LogicaDeProgramacao
/Aula11/Dicionario.py
501
3.578125
4
familia1 = [('Paulo',29),('Morgania',24),('Hadassa',3)] familia = dict(familia1) pais = {'Pai':'Iremi','Mãe':'Odalesa','Irmã':'Alana'} toda= {} ''' print(familia1[1][1]) print() print(familia) print(familia.get('Hadassa'))''' for (k,v),(k2,v2) in zip(familia.items(),pais.items()): print(k,'-',v) print(k2,'-',...
d9525dc3aad2d3bea52f7bd70ddbb78fd6c6ea7a
MarcosMon/Python
/Codewars/Kata7/Banking_class.py
1,189
3.921875
4
class User(object): def __init__(self, name, balance, checking_account): self.name = name self.balance = balance self.checking_account = checking_account def withdraw(self, money_withdraw): if money_withdraw > self.balance: raise ValueError() self.mon...
b6de0912b8042eb68e3a90f41fdf6eaac6ed47d5
Michellinian/unit-3
/Week29/task2.py
433
4
4
# Write a Python program that generates random passwords of length 20. # The user provides how many passwords should be generated import string, random usrinput = int(input()) lett = string.ascii_letters num = string.digits punct = string.punctuation allchar = lett + num + punct for x in range(1, usrinput+1): pw...
134610466ca7ed40e2cd01a4733787e4f588314b
ServioTRC/CodeFights_Solutions
/Arcade/Intro/Exploring the Waters/palindromeRearranging.py
379
3.5625
4
def palindromeRearranging(inputString): letras = [0 for _ in range(26)] for i in inputString: letras[ord(i.lower())-97] += 1 impar = False if len(inputString) % 2 != 0: impar = True for val in letras: if val % 2 != 0: if impar: impar = False ...
266ee3d0d77628384d2760e245512133a9673269
afsalcodehack/leetcode
/Interview/KMostFrequentElements.py
415
4.15625
4
# K Most Frequent Elements # input: [1,6,2,1,6,1,6], k=2 # output:[1,6] # # k1 = will be 1 and k=2 will be 6 so bothe are same count(3) # in this case combine together def most_freq_num(ar, k): dict = {} for i in ar: if i in dict: dict[i] = dict[i] + 1; else: dict[i] = ...
b5f1c955ad5ce1634d9d62fecce5e22276213217
jnoas123/python
/oef sequence 1/oef_7.py
193
3.984375
4
number = 15 print('the starting number is 15') number *= 10 print(number) number += 5 print(number) number -= 7 print(number) number += 1 number *= 100 print(number) number //= 2 print(number)
2a6d4d1d3e5f04499baa2eebb7f45c3e102d993f
chanyoonzhu/leetcode-python
/516-Longest_Palindromic_Subsequence.py
1,145
3.828125
4
""" - https://leetcode.com/problems/longest-palindromic-subsequence/ - intuition: greedily match from two ends into middle """ """ - dynamic programming (top-down) - O(n^2), O(n^2) """ class Solution: def longestPalindromeSubseq(self, s: str) -> int: @lru_cache(None) def dp(i, j): ...
9d7de9e9233063d2b8ebd0f968d7cdc6169cdf03
inverseundefined/DataCamp
/Regular_Expressions_in_Python/03-Regular_Expressions_for_Pattern_Matching/09-Invalid_password.py
1,335
4.25
4
''' Invalid password The second part of the website project is to write a script that validates the password entered by the user. The company also puts some rules in order to verify valid passwords: It can contain lowercase a-z and uppercase letters A-Z It can contain numbers It can contain the symbols: *, #, $,...
723f4bb634b5edf0dd63786516a3ec391410c844
Ryan-lee0217/Python-jeffrey0912
/untitled21.py
322
3.75
4
# -*- coding: utf-8 -*- """ Created on Sat Nov 28 15:05:47 2020 @author: ryanl """ import tkinter as tk window = tk.Tk() window.geometry("300x300") for i in range(1,10): for j in range(1,10): l = tk.Label(window,text=i*j) l.grid(row=i,column=j,padx=5,pady=5) window.mainloop() ...
6ad99ca0a227e02cf664cb0f10516d5a31021da9
fornutter/git_test
/python_example/0011/0011.py
399
4.03125
4
# 敏感词屏蔽 import string def open_file(name): b=[] with open(name,"r") as f: f=f.readlines() for i in f: i=i.strip() b.append(i) return b def decide(str,ListWord): if str in ListWord: print("Freedom") else: print("Human Rights") if __name__ == "__main__": yourWord=input("please input your word:...
2f82c2a75a14fdca740fc0ee2453952e35ab6b5b
Franktian/leetcode
/addDigits.py
209
3.859375
4
def addDigits(num): if num < 10: return num s = sumOfDigit(num) return addDigits(s) def sumOfDigit(num): s = 0 while num != 0: s += num % 10 num /= 10 return s
0c8c491aa4b16d8690585ad0675ec3931db16ecb
reevesba/computational-intelligence
/projects/project3/src/max_func/mf_mutate.py
1,430
3.5
4
''' Function Maximization Mutator Author: Bradley Reeves, Sam Shissler Date: 05/11/2021 ''' from numpy import random from typing import List, TypeVar MaxFuncMutator = TypeVar("MaxFuncMutator") class MaxFuncMutator: def __init__(self: MaxFuncMutator, length: int, mutation_prob: float) -> None: ...
de90b598e1bccd7980b5918da1f8f2f5bd967e06
HelenaOliveira1/Exerciciosprova2bim
/Questão 40.py
1,236
3.828125
4
print("Questão 40") print("") codigo = int(input("Digite o Código da Cidade: ")) veiculos = int(input("Digite o número de veículos de passeio (em 1999): ")) acidentes = int(input("Digite o número de acidentes de trânsito com vítimas (em 1999): ")) MA = acidentes ME = acidentes soma = 0 soma2 = 0 aux = 1 ccm = codigo c...
6ae07cc5c0f2161166169f008167e0ec69b6b7db
melvz/frisby
/object-oriented-exercise/main_bank.py
1,737
3.984375
4
from bank_account import Account ACCOUNTS = {} show_menu = True while(show_menu): print "1 - CREATE account" print "2 - VIEW accounts" print "3 - WITHDRAWAL" print "4 - EXIT" selection = raw_input("Select Action: ") if selection == "1": name = raw_i...
8da54b6556a56b49e593a17121b86df269a95b4c
vigorousyd168/leetcode
/Python/374GuessNumberI.py
853
3.875
4
# 374 Guess Number Higher or Lower I # The guess API is already defined for you. # @param num, your guess # @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 # def guess(num): number = 7 def guess(num): if num < number: return 1 elif num > number: return -1 els...
7c51ec1ce587446cc86843bac03cca177c28207d
GjjvdBurg/ffcount
/ffcount/__init__.py
1,458
3.75
4
# -*- coding: utf-8 -*- __version__ = "0.1.5" # Author: Gertjan van den Burg <gertjanvandenburg@gmail.com> # # License: Apache License 2.0 from pathlib import Path from typing import Tuple from typing import Union from .count import fast_file_count def ffcount( path: Union[str, bytes, Path] = ".", recurs...
3c33b4e84743a21e1b12794b4e3a6a309ae8ba37
sthefanni/pythonrepeticao
/questao2.py
194
3.578125
4
login = input("login: ") senha = input("senha: ") while login == senha: print("sua senha deve ser diferente do login: ") senha = input("senha: ") print("resposta válida")
8d05ab89d96a42ac71de3b0d1ece0f4aaebdf409
treedbox/python-3-basic-exercises
/concatenate/app.py
687
3.859375
4
"""Concatenation.""" def bar(name, times): """Hello many times in many languages.""" print('Hello', name, times, 'times!') # it's not concatenated but seems like print('Hallo %s %s mal!' % (name, times)) print('Bonjour ' + name + ' ' + str(times) + ' fois!') print('こんにちは {name} {times}回!'.format(...
d8c0d059ac676203ebd29bfdd22809b5e8fb292b
liyi0206/leetcode-python
/231 power of two.py
401
3.828125
4
class Solution(object): #def isPowerOfTwo(self, n): # """ # :type n: int # :rtype: bool # """ # if n<=0: return False # while n>1: # m =n%2 # if m==1: return False # else: n /= 2 # return True def isPowerOfTwo(self, n): ...
10c60d63373a72135749d3e0433c0ccef04f13a8
AlejoJorgeGonzalez/DS_A02_Basico_de_Python
/c27_adivina_el_numero.py
926
4.1875
4
# Se utiliza módulos, los módulos de python son códigos # que los mismos desarrolladores de python han realizado para # nosotros, son funciones que permiten ahorrar tiempo y trabajo # en la escritura de nuestro código, para llamarlos usamos la # palabra reservada import # El módulo ramdom es el diseñado para funcion...
04eacefca9fae1436fe64cdee379d5143c34b221
JavonDavis/Competive-Programming-Python
/hackerrank/competitions/rookierank3/comparing_times.py
974
3.71875
4
#!/bin/python import sys def timeCompare(t1, t2): t1 = t1.split(":") t2 = t2.split(":") decider1 = t1[1][-2:] decider2 = t2[1][-2:] if decider1 == "AM" and decider2 == "PM": return "First" elif decider2 == "AM" and decider1 == "PM": return "Second" else: decider1 =...
e2661f4d33cfe58e3b18b4b65cc16525eb806a51
RowanArland/90-beginner-python-programs-
/quest77.py
199
3.671875
4
exp77list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n'] def listslicing(S, slicing): return [S[i::slicing] for i in range(slicing)] print(listslicing(exp77list,3))
9aa87bd965074921c0e4b45a67d858cd8d02f09d
ralphtatt/project-euler
/problem_007.py
716
4.0625
4
""" Problem 7: By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? """ def is_prime(num: int, primes: list[int]) -> bool: # This is assuming the list 'primes' contains all lower valued prime numbers for i in primes: ...
e263907afdecddd84d6f35fdbab589400a32a0a5
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/thomasvad/lesson3/slicinglab.py
1,234
4.1875
4
def seq1(seq): '''swaps th first and last items of a sequence''' newseq = seq[-1:] + seq[1:-1] + seq[:1] return newseq def seq2(seq): '''returns every other item removed''' newseq = seq[::2] return newseq def seq3(seq): '''removes the first 4, last 4 and every other item''' newseq =...
26d00be2e331610824d1e29d00da279be80b49a2
rafaelacarnaval/uri-online-judge
/uri_1008.py
156
3.71875
4
numero = int(input()) horas = int(input()) valor = float(input()) salario = horas * valor print("NUMBER = %d" %numero) print("SALARY = U$ %.2f" %salario)
19d0b2b7c377fe41451fe92a99b7961ee5eb568e
getabear/leetcode
/git.py
2,185
3.90625
4
# 这是一个测试 class ListNode: def __init__(self, x): self.val = x self.next = None class lian: def creat(self,nums): #构造一个链表的函数 ret=ListNode(-1) res=ret for i in nums: ret.next=ListNode(i) ret=ret.next return res.next def display(self,he...
b055a7e7d4c44ed9d18eb777fce43d337518671f
imichaelnorris/LindoParser
/lindoparse.py
3,276
3.984375
4
import sys import string EQUALITY = ['=', '<=', '>=', '<', '>'] def lhs(line): '''move variables to left of equals sign''' if (not '=' in line): return line temp = line.split(' ') for i in EQUALITY: if i in temp: equalsLocation = temp.index(i) #print('equalsLocation {0}...
98d107db396e68ee1a3c97fbc5caacbb2fa0cece
ParkKeunYoung/py_projects
/basic/p4.py
1,148
3.796875
4
''' > 딕셔너리 : {} -> , js의 객체와 동일, 순서 x, 키: 값, 키는 중복되면 안됨, 값 중복은 허용 => 테이블상의 한 개의 row,json의 객체 ''' # 이 스타일을 가장 많이 사용 dic = {} print(dic, len(dic), type(dic)) dic = dict() print(dic, len(dic), type(dic)) ########################################...
69f7ad020546ec1c39fac6138c1377e27627b9f9
ManaTagawa/GitHubTest
/Make_matrix.py
1,795
3.515625
4
import torch import itertools # '1'で作成 # >>> Make_matrix_one(3) # tensor([[1, 0, 0], # [0, 1, 0], # [0, 0, 1], # [1, 1, 0], # [1, 0, 1], # [0, 1, 1], # [1, 1, 1]]) def Make_matrix_one(x_num): # 説明変数の数 x_list = list(range(0,x_num)) # [0, 1, 2, ..., x...
7208c16d2466136300a4b15713edbc86c914403f
elsa7718/sc101-2020-Nov
/Upload/boggle/sierpinski.py
2,797
3.875
4
""" File: sierpinski.py Name: --------------------------- This file recursively prints the Sierpinski triangle on GWindow. The Sierpinski triangle is a fractal described in 1915 by Waclaw Sierpinski. It is a self similar structure that occurs at different levels of iterations. """ from campy.graphics.gwindow import G...
5867fe28acdc985097c259ffd9b9832cda10fd30
lyzlovKirill/Geek-pyton
/task6.3.py
1,966
3.546875
4
#Реализовать базовый класс Worker (работник), в котором определить атрибуты: name, surname, position (должность), # income (доход). Последний атрибут должен быть защищенным и ссылаться на словарь, содержащий элементы: оклад и премия, # например, {"wage": wage, "bonus": bonus}. Создать класс Position (должность) на ба...
9c03324049c2f5d2027c0c5458cf8fb4e391aefd
sivasant/python_project
/python/if_statement.py
130
3.9375
4
x=5 y=6 z=7 if x<y: print(x) if x>y: print(x) elif y>z: print(y) elif(y>3): print(y) else: print(z)
80014b9c75b560997e6b54454f3c2bd5091ae516
Kaushik8511/Competitive-Programming
/Graph algos/sudoku.py
694
3.859375
4
row_hash_table = [[0 for i in range(9)]for j in range(9)] col_hash_table = [[0 for i in range(9)]for j in range(9)] sudoku = [[0 for i in range(9)]for j in range(9)] while True: for i in sudoku: for j in i: print(j,end=' ') print() print() row = int(input("enter row : ")) col = int(input("enter col...
bf931738c47f7598cb298f83b08a6cfdfaea53f3
alexmaclean23/Python-Learning-Track
/12-InputOutput/InputOutput.py
1,559
4.4375
4
# Declaration and opening of a file myFile = open("Python-Learning-Track/12-InputOutput/sampleFile.txt") # Reading the contents of a file as a String myFile.seek(0) print(myFile.read()) print() # Reading the contents of a file as a List myFile.seek(0) print(myFile.readlines()) print() # Closing file at end of use <I...
fa0c011c21108bcb437cf2bc82755d23b2f35882
smdaa/project-euler
/p3.py
378
3.625
4
#Largest prime factor #Problem 3 def is_prime(n): for i in range(2, n - 1): if (n % i == 0): return False return True def compute(): n = 600851475143 max = 1 for i in range(2, n - 1): if (is_prime(i) and n % i == 0): if (max < i): max = i ...
4a1b64e11c3d9459172e80115c8dd31a8df643a6
slavonicsniper/learn-python
/emoji-exercise-1.py
262
3.84375
4
import emoji ## ##message = input(">") ##words = message.split(' ') ##emojis = { ## "smile": ":thumbs_up:", ## "sad": ":water_wave:" ##} ## ##output = "" ##for word in words: ## output += emojis.get(word, word) + " " print(emoji.emojize(':thumbs_up:'))
70ff111ef1bf829eefe56edaa22b58421a3cf4b2
nsilver7/imperva
/imperva.py
2,738
3.625
4
#!/usr/bin/env python import requests from requests.auth import HTTPBasicAuth from getpass import getpass import json import sys def authenticate(session, server): """ This function authenticates a requests.Session object. Parameters ========== session: requests.Session object This is the session instan...
ce5d93e4059ce2fa7fddd386b317560528a3aab9
charliealpha094/Project_Data_Visualization
/Chapter_15_Generating_Data/try_15.6/dice_2D8_visual.py
1,292
3.859375
4
#Done by Carlos Amaral (21/08/2020) #Try 15.6 - Two D8's """ Create a simulation showing what happens when you roll two eight-sided dice 1000 times. Try to picture what you think the visualization will look like before you run the simulation; then see if your intuition was correct. Gradually increase the number of r...
f118dc06c4fcd3fc1136648adc5f3a39b570cb55
igor376/CoffeeMachine
/Coffee Machine/task/machine/coffee_machine.py
6,965
4.34375
4
# water = int(input("Write how many ml of water the coffee machine has:\n")) // 200 # milk = int(input("Write how many ml of milk the coffee machine has:\n")) // 50 # beans = int(input("Write how many grams of coffee beans the coffee machine has:\n")) // 15 # cups_needed = int(input("Write how many cups of coffee you w...
958145730877de8fb1af8562ef9c1595ea006553
Baasant/DATA-STRUCTURES-AND-ALGORITHMS-SPECIALIZATION
/Tool box/week3/maximum_salary.py
970
3.96875
4
# python3 from itertools import permutations def largest_number_naive(numbers): numbers = list(map(str, numbers)) largest = 0 for permutation in permutations(numbers): largest = max(largest, int("".join(permutation))) return largest def is_greater(digit, max_digit): return digit + max...
25be9c5ee03f3d3d88f60e903f69607a29085292
jermynyeo/Advent-Of-Code
/adventofcode2.py
712
3.625
4
with open('adventofcode2_input.txt','r') as file: number_three = 0 number_two =0 for lines in file: lines = lines.rstrip("\n") #checking char char_dict = {} for ch in lines: if ch not in char_dict: char_dict[ch] = 1 else: ...
be484e2e6449a281bc0a61cffe807f5cd4c6769a
Vanditg/Leetcode
/Single_Number_II/EfficientSolution.py
774
3.78125
4
##================================== ## Leetcode ## Student: Vandit Jyotindra Gajjar ## Year: 2020 ## Problem: 137 ## Problem Name: Single Number II ##=================================== #Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that sing...
5d4b36f2004d2c6f34513c86681fa4468ef155bb
liu666197/data1
/8.17/08 对象的嵌套.py
992
3.78125
4
# 5.模拟英雄联盟中的游戏人物的类: # 要求: # a.创建Role(角色)类 # b.初始化方法中给对象封装 name,ad(攻击力),hp(血量)三个属性 # c.创建一个attack方法,此方法是实例化的两个对象,互相攻击的功能 # 例: # 实例化一个Role对象,盖伦,ad为10,hp为100 # 实例化另一个Role对象,亚索,ad为20,hp为80 # attack方法要完成: '谁攻击谁,谁掉了多少血,还剩多少血的提示功能' class Role: def __init__(self,name,ad,hp): self.name = name ...
148e2c2cf65ee27984d3f19ff63bfc461e0d13d5
radiocrew/test_part_2
/two_stack_one_que.py
1,019
3.875
4
#https://www.youtube.com/watch?v=t45d7CgDaDM class Node: def __init__(self, data): self.data = data self.next = None pass def next(self): return self.next def next(self, data): self.data = data class Stack: def __init__(self): sel...