blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
7ad07e51fefa4c5118192f6bab9b52c4fe3aa542
mouyang2001/SOFTENG-284
/assignment-1/task1.py
748
3.609375
4
# Author: Matthew Ouyang # Task: find the maximum profit from a list of stock prices # Commands to execute code: # > python3 task1.py < canvas.in > myout1.txt # > diff myout1.txt canvas.out1 import sys # more efficient solution O(n) def find_max_profit(prices, length): max_profit = prices[1] - prices[0] min_price...
53d7acce0c9cbdc2b171ede0a72f9207d7a19f01
jaychsu/algorithm
/lintcode/611_knight_shortest_path.py
1,336
4.03125
4
""" Definition for a point. class Point: def __init__(self, a=0, b=0): self.x = a self.y = b """ class Solution: V = ( (-2, -1), ( 2, 1), (-2, 1), ( 2, -1), (-1, -2), ( 1, 2), (-1, 2), ( 1, -2), ) """ @param: G: a...
f6ca0ba07ae817412cd3c200e61d8cd4ca111b14
hun-a/learn-the-python-basic
/src/03.list.py
1,158
4.09375
4
# https://wikidocs.net/14 # List odd = [1, 3, 5, 7, 9] a = [] b = [1, 2, 3] c = ['Life', 'is', 'too', 'short'] d = [1, 2, 'Life', 'is'] e = [1, 2, ['Life', 'is']] print(a, b, c, d, e) # Indexing and slicing print(b[0], b[1], b[2]) print(b[0] + b[1] + b[2]) print(b[-1]) a = [1, 2, 3, ['a', 'b', 'c']] print(a[0]) prin...
6c741be9668e504c84b48a0d27aba7f6fe0a1d1b
Mandeep5138/Study
/PYTHON CODES/Rolling_Hash_String_compare.py
646
3.71875
4
text = "Python" pattern='th' X=len(text) Y=len(pattern) d=256 #positional base #sum for pattern sumP=0 for i in range(Y): sumP=sumP+(ord(pattern[i])*(d**(Y-i-1))) print(sumP) #sum of text sumT=0 flag=0 for i in range(Y): sumT=sumT+(ord(text[i])*(d**(Y-i-1))) if sumP==sumT: print("Patt...
5def0d88a071d4d836e66fbbeac357caa6ae7c5c
handabaldeep/leetcode
/arrays/two_sum.py
392
3.546875
4
# Link - https://leetcode.com/problems/two-sum/ from typing import List class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: nums_idx_dict = {} for i in range(len(nums)): if target - nums[i] not in nums_idx_dict: nums_idx_dict[nums[i]] = i ...
6272690c68253082e2596ad3de8b375f7c9478cd
spacecase123/cracking_the_code_interview_v5_python
/18.4_number_of_2s.py
881
3.953125
4
''' Write a method to count the number of 2s between0 and ''' def num_2s_brute_force(n): twos = 0 for i in range(2, n+1): x = str(i) for j in range(len(x)): if x[j] == "2": twos += 1 return twos def num_2s(n): if n < 2: return 0 twos = 0 ...
860dc28d80a0e9a631b3731afcc3a303fbaa6f3d
SATHANASELLAMUTHU/MYPROJECT
/B72.py
171
3.734375
4
n=input("Enter the sentence:") c=0 for i in n: if(i=="a" or i=="e" or i=="i" or i=="o" or i=="u"): c=c+1 if c==0: print("No") else: print("Yes")
ffc943eab1f639db284c2a79e3087344d1f8f076
kagerman80/Recursion
/recursion.py
455
4.125
4
"""Digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. The input will be a non-negative integer.""" def calc_digits(x): result = sum(list(map(int,s...
aa60daaec83b46ef58da28f6f6219701855c8e86
kevinlondon/leetcode
/0000-0999/026_remove_duplicates_from_array_easy.py
463
3.5625
4
class Solution: def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ unique_nums = sorted(list(set(nums))) length = len(unique_nums) print(unique_nums) for index in range(len(nums)): if index < length: ...
5201720365f8967343fbe88a073f3c3ef654c665
jonliu6/Programming
/PythonDemo/interests.py
659
3.5625
4
initialAmount = 100 annualAmount = 10 interests = 0.1 asset = 0 #for x in range(0,20): # asset = (initialAmount + annualAmount * x) * (1 + interests) ** x #asset = (initialAmount) * (1 + interests) ** x # with a fixed initial amount, no annual deposite #print("year", x, ", asset=" , asset) # print(asset) def...
e4a009b37ed9a3c8a625664d88d02e87c5044709
asifbux/Python-Course-ENSF-592
/Assignment4/A04_analyze_book1.py
2,652
3.78125
4
"""This module contains a code example related to Think Python, 2nd Edition by Allen Downey http://thinkpython2.com Copyright 2015 Allen Downey License: http://creativecommons.org/licenses/by/4.0/ """ from __future__ import print_function, division from Histogram import Histogram as hg import string def process_f...
e88b4192ce368b93ab88f978bc3649fd3d16b242
psycho-pomp/CodeChef
/KS2.py
270
3.703125
4
# cook your dish here def sum_digits(n): return sum(map(int, str(n))) def findRoundNumber(order): s = sum_digits(order) % 10 return order * 10 + (0 if s == 0 else (10 - s)) t=int(input()) for _ in range(t): n=int(input()) print(findRoundNumber(n))
aa513a0a1b66b4f40a5dac8e83a14ee5767272ed
Nuttanan29445/Python-Daily
/Day028.py
932
3.515625
4
def readword(n): read = ['soon','neung','song','sam','si','ha','hok','chet','paet','kao'] return read[n] def to_Thai(n): ans = '' k = n if k == 0 : ans+=readword(k) else : if len(str(n))>3: p = k//1000 if p>0 : ans+=readword(p) ans...
cba8fa8380a41c876bbd89f23cd134abfb40f731
irina-baeva/algorithms-with-python
/data-structure/queue.py
589
3.828125
4
class Queue: def __init__(self, head=None): self.storage = [head] def enqueue(self, new_element): self.storage.append(new_element) def peek(self): return self.storage[0] def dequeue(self): return self.storage.pop(0) # Setup q = Queue(12) q.enqueue(20) q.enqueue(1...
3abfb0c19e5398bab0b3b2618242d562ab9f6330
IveDeletedYourPostAsItsADuplicate/codonPython
/codonPython/suppression.py
1,381
3.9375
4
def central_suppression_method(valuein: int, rc: str = "5", upper: int = 5000000000) -> str: """ Suppresses and rounds values using the central suppression method. If value is 0 then it will remain as 0. If value is 1-7 it will be suppressed and appear as 5. All other values will be rounded to the ...
60a87e5fbc228c7dcc0c2c4d303d9855c95e94ec
PedroPadilhaPortella/Curso-Em-Video
/Curso de Python Mundo 2/055-estatistica.py
662
3.765625
4
olderName = '' older = 0 sumAges = 0 youngWomen = 0 for pessoa in range(1, 5): print(f"-----{pessoa} PESSOA-----") nome = input(f"Nome da Pessoa {pessoa}: ") idade = int(input(f"Idade da Pessoa {pessoa}: ")) sexo = input(f"Sexo da Pessoa {pessoa} [M/F]: ").strip().upper() sumAges += idade if(ida...
9bf8325a657b4848a1ec8330a19c74eb0e4ecae9
patil16nit/algorithms
/algorithm/permutationPalindrom.py
559
3.59375
4
def permutationPalindrom(msg, start, end): if start == end: print ''.join(msg) else: for i in xrange(start, end+1): msg[start], msg[i] = msg[i], msg[start] permutationPalindrom(msg, start+1, end) msg[start], msg[i] = msg[i], msg[start] def main():...
afee1c02dfa24cfa0350c399990dd1c047923107
ww-tech/primrose
/primrose/transformers/categoricals.py
6,727
3.546875
4
"""Module to run a basic decision tree model Author(s): Mike Skarlinski (michael.skarlinski@weightwatchers.com) """ import pandas as pd import numpy as np import logging from sklearn import preprocessing from primrose.base.transformer import AbstractTransformer class ExplicitCategoricalTransform(AbstractTransf...
c142babbbfdefbf54f5b53b511e7630aa3e726b4
Mehedi-Hasan-NSL/Python
/bfs_shortest_reach.py
2,208
3.90625
4
# -*- coding: utf-8 -*- """ Created on Wed Jul 7 17:09:46 2021 @author: DELL """ from collections import defaultdict # This class represents a directed graph # using adjacency list representation class Graph: # Constructor def __init__(self): # default dictionary to store graph ...
b47e77a5dc42c5fd191af10f58195c9a6df2286c
ZunLayNwe12/GitSample
/Variable.py
1,946
4.3125
4
#21.12.2019 >>> text = "This is a string" >>> text 'This is a string' >>> 2 + 2 4 >>> 50 - 5 * 6 20 >>> (50 - 5 * 6) / 4 5.0 >>> round(5.0) 5 >>> 5.123456 5.123456 >>> round(5.123456,2) 5.12 >>> 17 / 3 # division returns a float 5.666666666666667 >>> 17 // 3 # discards the fraction 5 >>> 17 % 3 # ...
e67835f8263a0934afbb015f4eaf51f2479c0b98
zaid-sayyed602/Python-Basics
/star patterns with for loop.py
3,942
4
4
n=int(input("Enter the number of lines you want\n:")) print("1") for i in range(n): for j in range(i+1): print("*",end="") print() print("\n") print("\n") print("2") for i in range(n): for j in range(n-i-1): print(" ",end="") for k in range(i+1): print("*",end=...
e6cc8873afeac49f80de87d51e221dd982dea1f9
roisinhanlon/hello-world
/whilecounter.py
81
3.578125
4
counter = 0 while counter < 5: counter +=1 print(counter, 'test loop')
4d1455a28a83758176391f13a392f9590d2c10ab
ahmedzaabal/Python-Demos
/functions.py
796
3.984375
4
from datetime import datetime #this is a functions current date and time #custom messages # def print_time(task_name): # print(task_name) # print(datetime.now()) # print() # first_name = "Ahmed" # print_time("task is done") # for x in range(0, 10): # print(x) # print_time("Task is done") def ge...
ae6c737b08c1eff5d4e169eef23c7db9455d737a
LeunamBk/MSC
/regmod/pcaPython/argvValidate.py
314
3.734375
4
# validate user input import sys def validateArgv(argv): def is_intstring(s): try: int(s) return True except ValueError: return False for arg in argv: if not is_intstring(arg): sys.exit("All arguments must be integers. Exit.")
3254a02f11d8420fd64cc069f47a879d4108775c
sky-bot/Interview_Preparation
/LeetCode/Binary_tree_paths.py
825
3.734375
4
class Solution: def binaryTreePaths(self, root: TreeNode) -> List[str]: all_paths = list() if root.left is None and root.right is None: return [str(root.val)] self.inorder(root.left, str(root.val), all_paths) self.inorder(root.right, str(root.va...
a4b9949e0c7e9e01bcd704589b6edcbdab540c0b
tzkcnm/test
/python_lecture_20161028/context_manager.py
809
3.78125
4
# -*- coding:utf-8 -*- # class SkipMe(Exception): # pass SkipMe = type('SkipMe', (Exception,), {}) class ContextManager(object): def __enter__(self): print '=== START ===' def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is SkipMe: return True print '=== END ...
8db2f626046f6cbcc3037e5e2fc513b9e8cf88d1
lujin123/algorithms
/leetcode/python/remove_linked_list_elements.py
1,315
3.875
4
# Created by lujin at 3/3/ # # 203. Remove Linked List Elements # # Description: # # Remove all elements from a linked list of integers that have value val. # # Example # Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 # Return: 1 --> 2 --> 3 --> 4 --> 5 # class ListNode(object): def __init__(self, x): ...
6bfaf0fd0dc86d3d408d03319f2e2751e385706b
mfkiwl/Sanajeh
/src/call_graph.py
7,927
3.53125
4
# -*- coding: utf-8 -*- # Define Python call graph nodes' data structure from typing import Set # Block tree Node class CallGraphNode: node_count = 0 def __init__(self, node_name): self.name: str = node_name # node name self.declared_variables: Set[VariableNode] = set() # varia...
f8515820f299607c0b8ec6a4f5988e175fe9f5f5
Subhajit-Roy-18/Mensuration
/Mensuration.py
4,831
4.34375
4
print("This is a program which will help you in Mensuration.") print("NOTE: While you Input the Measurements, DO NOT TYPE ITS UNIT. \n") def main(): print("On which Topic do you want help in ?") print("For Perimeter, Type 1.") print("For Area, Type 2.") print("For Volume, Type 3.") Type...
51eed8ad2f705c8e9d872a2ff9cb6245f0b5fb44
mpkuchera/PHY200_homeworks
/Homework5/intensity.py
1,262
3.75
4
""" name: intensity.py Compute and visualize diffraction of waves upon encountering a straight edge. Problem 5.11 from Newman's Computational Physics. author: Darcy Lewis date created: 15/3/2021 """ # Reminder: you can create other helper functions as long as the function # behaviors below remain the same #...
c5e51a72df7a385de192d1721d28d11385249961
iakonk/MyHomeRepos
/python/examples/leetcode/easy/find_smallest_contigius_subarr.py
609
3.59375
4
def find_max_freq(arr): window_start, max_freq = 0, 0 numbers_freq = {} for window_end in range(len(arr)): right_num = arr[window_end] numbers_freq.setdefault(right_num, 0) numbers_freq[right_num] += 1 while len(numbers_freq) > 1: left_num = arr[window_start] ...
89f7b5212b15c7540d786400e44793ced58c2cfa
ncrubin/NielsenNNBookExercise
/network.py
5,664
4.40625
4
'''' Feed forward neural network from Michael Nielsen's book on deep learning http://neuralnetworksanddeeplearning.com/ Network is set up as number of layers and a list of sizes. The weights and biases for network are selected at random. The cost function is quadratic. This program demonstrates a simple neural n...
c59d570c507ebb1c3c67ddd04bb3fb9a4d8629c1
mohinishmd/Speech-Recognition-Python
/wav_transcribe.py
821
3.8125
4
import speech_recognition as sr # obtain path to "english.wav" in the same folder as this script from os import path WAV_FILE = path.join(path.dirname(path.realpath(__file__)), "microphone-results.wav") # use "english.wav" as the audio source r = sr.Recognizer() with sr.WavFile(WAV_FILE) as source: audio = r.reco...
c1db1a2125e0c87fc0b10d8d3c7ee41e07cad3ed
hegde10122/python_training
/numpy/numpy6.py
2,700
4.4375
4
''' INDEXING AND SLICING of ndarrays ''' import numpy as np arr = np.arange(10) print(arr) print(arr[5:8]) #index 8 is not included ---only 3 elemnts at index 5,6,7 arr[5:8] = 19 print(arr) ''' If you assign a scalar value to a slice, as in arr[5:8] = 19, the value is propagated (or broadcasted henceforth) to the ...
a3c448ce545883a8b5cd713ac47ca825c40c2a1d
swordwielder/python3
/printdiamond.py
390
3.921875
4
n = int(input()) print(n*'#') for i in range(1, (2*n+1)//2 + 1): for j in range((2*n+1)//2 - i): print(" ", end = "") for k in range((i*2)-1): print("#", end = "") print() for i in range((2*n+1)//2 + 1, 2*n + 1): for j in range(i - (2*n+1)//2 -1): print(" ", end = "") for k ...
a04466fc4c154a59dd983fe4a56befe8b530be68
huwanping001/Python
/chapter4/demo9.py
225
3.8125
4
# 学校:四川轻化工大学 # 学院:自信学院 # 学生:胡万平 # 开发时间:2021/9/18 15:00 age = int(input('请输入你的年龄:')) if age: print(age) else: print('年龄为:', age)
c9296d6322695116decd3cc66604a16fae3f3a30
Slendercoder/Triqui
/my_app/funciones_logica.py
13,988
3.5625
4
import re conectivos = ['O', 'Y', '>', '='] Nfilas = 3 Ncolumnas = 3 Nnumeros = 3 Nturnos = 2 class Tree(object): def __init__(self, label, left, right): self.left = left self.right = right self.label = label def inorder(A): #Convierte un Tree en una cadena de símbolos #Input: A, ...
c2da35c69dbc9990c64b9d228fc5a68059486bca
jiinmoon/Algorithms_Review
/Archives/Leet_Code/Old-Reviews/Current-Reviews/Top-Review-01/0179-Largest-Number.py
421
3.671875
4
# 179 Largest Number # # We create a custom comparator that compares by string concatenation. from functools import cmp_to_key class Solution: def largestNumber(self, nums): def larger(a, b): return -1 if a + b > b + a else 1 nums = map(str, nums) nums.sort(key=cmp_to_key(larg...
9e1dd814bbc4e447b48cd212ac51444085b650e6
Bublinz/Python-Expert
/Exercises/student_fidel/triangle.py
319
4.0625
4
# write a program that will calculate the area of a traingle print('calculate the area of a triangle') def rate(length): b = int(input('Input the Base: ')) h = int(input('Input the Height: ')) # area = 0.5 * b * h area = 0.5 * b * h print('The area of the triangle is ' + str(area)) rate('length')
333e740a6f337c4bbc1d107ad2aef8146905098f
Bansi-Parmar/Python_Basic_Programs
/python_program-062.py
275
3.671875
4
## 62. 1 ## 2 2 ## 3 3 3 ## 4 4 4 4 ## 5 5 5 5 5 print('\n\t patterns') print('\t...........\n') n = int(input("Enter No of Rows :- ")) i=0 for r in range(1,n+1): print((('{} '.format(r)*r) .ljust(n*2))) i=i+1
44b93eaafdb68529be2bae98d6b00d67317c3b21
vitaedrinker/python
/JohnEmailScrape.py
882
3.890625
4
# read a webpage import urllib2 response = urllib2.urlopen('http://python.org/') html = response.read() import re #Regex #Author: John Nicholson #Scrapes Webpage and pulls all lines with an email to a .txt def WebToTxt(): print ("Would you like to use a different url other than https://pastebin.com/n9phcmx4...
f3c3bc512463b91bf81ec035b760b41ee4b89eb3
walxc1218/git
/圆的周长面积.py
1,152
4
4
#打印圆的周长和面积 r = 3 p = 3.14 l = 2*p*r s = p*r**2 print("圆的周长是:",l,"厘米") print("圆的面积是:",s,"平方厘米") 在交互模式下查看当前作用域的所有变量 help("__main__") del 语句 作用: 用于删除变量,同时解除与对象的关联,如果可能则释放对象 语法: del 变量名1, is/is not 小整数对象池: cpython中,-5至256的数永远存在于小整数 id(x)函数 作用: 返回一个 练习: 1.在终端输出图形:    * *** ***** ******* 2.中国古代的称是16两一斤,请问古代的216两...
c2af09a3372d309a5c0e2a0349ea2a9ea3d1acba
L200184092/Praktikum-AlgoStruk
/Praktikum 8/5.py
957
3.78125
4
class PriorityQueue(object): def __init__(self): self.qlist = [] def isEmpty(self): return len(self) == 0 def __len__(self): return len(self.qlist) def enqueue(self, data, priority): entry = PriorityQEntry(data, priority) self.qlist.append(entry) def...
efcc91ae4fbbacb2e3d66a967c3dde6a51fd1b7b
senioryta/Python-OOP
/12_Super()/main.py
840
3.671875
4
# superclass class Estudent: # private class attribute __total = 0 # constructor __init__() def __init__(self,name,id,classroom): self.__name = name self.__id = id self.__class = classroom Estudent.__total += 1 # method def showinfo(self): print("{} \n\t id : {} \n\t class : {} \n".format(self.__name,...
bbac10925ea7bebbd6ddbdcd6cb460dc401acc40
VinayakBagaria/Python-Programming
/New folder/Highest Prime Factor.py
435
3.734375
4
#Largest Prime Factor def prime(a): for i in range(2,a): if a%i==0: return -1 return 1 def calc_prime(n): p=2 while p*p<=n: if (n%p==0 and prime(p)!=-1): n=n//p else: p=p+1 print(n) global take test=int(input()) list=[No...
c4e7ea0c065b5f60ef259afb67cb5503857ee448
bpull/fall16
/graphics/hw/4/circle.py
1,299
3.578125
4
#!/usr/bin/python3 # Our required libraries! import math from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * #drange definition taken from http://stackoverflow.com/questions/477486/python-decimal-range-step-value def drange(start, stop, step): r = start while r < stop: yield r ...
a0b687706fd97a4a69699b2aac6bf4b0365a912a
JSYoo5B/TIL
/PS/BOJ/11723/11723.py
857
3.65625
4
#!/usr/bin/env python3 from sys import stdin input = stdin.readline if __name__ == '__main__': op_cnt = int(input()) sets = set() for _ in range(op_cnt): oper = list(input().split()) operation, operand = oper[0], 0 if len(oper) == 2: operand = int(oper[1]) ...
82d35b1f595648d45986f0d94fe041baf8538e5b
MartinGildea/tutorial2_primeFactor_competition
/martingildea_tutorial2_competition.py
981
3.875
4
# primeFactors.py # import test code from lab2Test import speedTestFun # -------------------------------- # primeFactors() # input: A positive integer n (e.g. 19162234) # output: A list of the prime factors of n with multiplicity (e.g. [2, 7, 7, 13, 13, 13, 89]) # method: Divide n by all possible integers in increasin...
f28640f6e7c1f8ab046edd4b0ee495fc24716bac
HongsenHe/algo2018
/036_valid_sudoku.py
3,468
3.71875
4
# 07282021 class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: rows = len(board) cols = len(board[0]) # verify each row for i in range(rows): visited = set() for j in range(cols): if not self.valid(board, i, j, vis...
854cc0ef95d03cb7b1f3d149ad445ef8a2b154ca
dnuffer/dpcode
/determine_if_one_string_is_a_permutation_of_another/python/start.py
608
3.984375
4
""" >>> are_permutations("abc", "cab") True >>> are_permutations("abc", "aab") False >>> are_permutations("abcd", "abc") False >>> are_permutations("", "") True >>> are_permutations("a", "a") True >>> are_permutations("aaa", "aaa") True >>> are_permutations("aaa", "aaaa") False >>> are_permutations("aab", "abb") False ...
65ea12ccd51b4bc5dd85300bf7a2ce962a20f704
AndyAtari/PyPong
/pong.py
2,806
3.8125
4
import turtle # window screen window = turtle.Screen() window.title("Pong by AndyAtari") window.bgcolor("black") window.setup(width=800, height=600) window.tracer(0) # player 1 paddle_one = turtle.Turtle() paddle_one.speed(0) paddle_one.shape("square") paddle_one.shapesize(stretch_wid=5, stretch_len=1) paddle_one.col...
92821beaaca67c43ac128590d27098ea30b250ef
Cyntha-K/bioinfo-lecture-2021-07
/0706/020.py
53
3.5
4
a = input('word1') b = input('word2') print(a + b)
b1a3712100763fe1b397d0bbe7624566e417b345
choco9966/Algorithm-Master
/programmers/level2/code/조이스틱.py
1,746
3.71875
4
# ord를 이용해서 알파벳의 위치를 출력하고 순차적으로 진행하는게 빠른지, 반대로 진행하는게 빠른 지 계산 def cal_change_alphabet(solution): diff = min(abs(ord(solution)-ord('A')), abs(26 - (ord(solution)-ord('A')))) return diff def change_alphabet(text, index): text_ = list(text) text_[index] = 'A' text = ''.join(text_) return text def...
a6629d987219ccf10ba4f10674bd7e890108c71b
111110100/my-leetcode-codewars-hackerrank-submissions
/hackerrank/plusminus.py
1,660
4
4
''' Given an array of integers, calculate the ratios of its elements that are positive, negative, and zero. Print the decimal value of each fraction on a new line with places after the decimal. Note: This challenge introduces precision problems. The test cases are scaled to six decimal places, though answers with abs...
b044ac8e0900ea8f23ccdf6b01f9f6c2b56640c7
15929134544/wangwang
/leetcode/14 最长公共前缀.py
1,274
3.515625
4
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ # # 思路一: # # 空字符串 # if not strs: # return '' # for index in range(len(strs[0])): # # 把第一个字符串的每个字母依次和后面每个字符串的字母做比较 #...
1a8556a871fa5a328ee8a0c600da163cb3d8277b
onitonitonito/k_mooc_reboot
/tortoise_hare.py
1,376
4
4
""" # finde duplicated number given an array nums containing n+1 integers where each inter is between 1 & n (inclusve) prove that at least one duplicate num must exist. Assue that there is only duplicate num but it could be repeated more than once. find the duplicate one. Example 1: - Input : [1,2,4,2,2] - Output: ...
a5494c7da9b4739273c40e84b05daeb06c8e3ae3
smitgabani/algorithms-python3
/sorting/selection-sort.py
323
3.71875
4
def selsort(A): r = len(A) for x in range(r): minimum = x for y in range(x + 1, r): if A[y] < A[minimum]: minimum = y (A[x], A[minimum]) = (A[minimum],A[x]) mylist = input('Enter the list values to be stored: ').split() selsort(mylist) print(mylist...
5f3b816c0dad6a85f6f79ed2f49a928aff9dc750
RianMarlon/Python-Geek-University
/secao7_colecoes/exercicios1/questao23.py
740
4.125
4
""" 23) Ler dois conjuntos de números reais, armazenando-os em vetores e calcular o produto escalar entre eles. Os conjuntos têm 5 elementos cada. Imprimir os dois conjuntos e o produto escalar, sendo que o produto escalar é dado por: x1 * y1 + x2 * y2 + ... + xn * yn """ lista1 = [] lista2 = [] for i in range(5): ...
2d68a23199e80a85907d665fd0af9f248e37e9a4
Sa4ras/amis_python71
/km71/Likhachov_Artemii/3/Task7.py
437
4
4
print('This program calculate the count of hours and minutes after 00:00') while True: X = input('Input minutes: ') try: if int(X) >= 0: h = int(X)//60 m = int(X)%60 print(h, 'hours', m, 'minutes') break else: print('Try again...
8a394b2e6973a1610215e78c524527c5e066bf60
ElcimarSilva/InterfaceGraficaPy
/main.py
620
4.09375
4
from tkinter import * def infos_no_print(): texto = "Esta é minha mensagem no método" texto_do_metodo["text"] = texto janela = Tk() janela.title("Minha janela criada em Python") # janela.geometry("400x400") texto_orientacao = Label(janela, text="Clique aqui para ver infos do método") texto_orientacao.grid(...
04e01661aa2d540993e644027e1791859de1016e
JaberKhanjk/LeetCode
/Array Problems/Sort Array By Parity II.py
547
3.5
4
class Solution(object): def sortArrayByParityII(self, A): n = len(A) odd = [] even = [] for each in A: if each % 2 == 0: even.append(each) else: odd.append(each) final = [0]*n ...
f04fc11d9f06c6deddca4bfc1d92e8f52739bd69
code-mic/Sololearn-Python-Core
/Fibonacci.py
163
4.15625
4
num = int(input()) def fibonacci(n): if n <= 1: return n else: return fibonacci(n-1) + fibonacci(n-2) for number in range(num): print(fibonacci(number))
14b6b7cfc759cdcb0ce848f67e576ebcdfe27070
DipendraDLS/Python_OOP
/14.Thread_&_Multithreading/13.Single_Tasking_Using_Thread.py
572
3.671875
4
''' - When multiple tasks are executed by a thread one by one, then it is called single tasking. ''' from threading import Thread from time import sleep class MyExam(Thread): def solve_questions(self): self.q1() self.q2() self.q3() def q1(self): print('Q1 Solved') s...
05f070ee2296e17882060d7350a55d9a2a50ba9f
hsnylmzz/Python-Learning
/pyt/set4.py
241
3.96875
4
def kume_dondur(str_kume: str): if str_kume.startswith("{") and str_kume.endswith("}"): kume_elemanlari = str_kume[1:len(str_kume) -1] v = kume_elemanlari.split(", ") print(v) kume_dondur("{1, 2, 3, 17}")
2b269158d03bb71c784dadfb2c877b56e9208618
ruchamahabal/TXP_Tech_Events
/codemapper/q1.py
740
3.75
4
def prime_list(l): result=[] flag = 0 for i in l: for j in range(2,i): if i%j!=0: flag = 1 else: flag = 0 break if flag == 1 or i==2 : if i not in result: result.append(i) return result ...
c76c43f407f7df9ed3497049e720eda7ec797f47
poojithayadavalli/String
/IMEI validation.py
1,759
4.25
4
""" International Mobile Equipment Identity (IMEI) is a number, usually unique, to identify mobile phones, as well as some satellite phones. The IMEI (15 decimal digits: 14 digits plus a check digit) includes information on the origin, model, and serial number of the device. The task is to validate IMEI in following ...
16272970aa5433ed7481251935efb29d3e76b981
sandeepkumar8713/pythonapps
/02_string/16_possible_space_in_string.py
1,848
4.34375
4
# https://www.geeksforgeeks.org/print-possible-inpStrs-can-made-placing-spaces/ # Question : Given a inpStr you need to print all possible strings that can be made by placing spaces # (zero or one) in between them. # # Input: str[] = "ABC" # Output: ABC # AB C # A BC # A B C # # Question Type :...
ade1dda398282ab6e380793e113a0186ccdd69a0
eucalypto/bitesofpy
/47/password.py
1,356
3.953125
4
import string PUNCTUATION_CHARS = list(string.punctuation) used_passwords = set('PassWord@1 PyBit$s9'.split()) def validate_password(password): if len(password) < 6: return False if len(password) > 12: return False # This is an alternative for characters that need only one appearance. ...
f4948d57dcfb16839e16488fedd316b5ab8b4732
j-d-0630/python
/a0323_binary_tree_doi.py
3,424
3.984375
4
""" Binary Tree 根付き二分木の表現 id left rightの情報が付与されたときに 節点の情報をその番号が小さい順に出力する node id, parent , depth, heigth Preorder Tree Walk 先行順巡回 根節点, 左部分木, 右部分木の順番 Inorder Tree Walk 中間順巡回 左部分木, 根節点, 右部分木の順番 Postorder Tree Walk 後行順巡回 左部分木, 右部分木, 根節点の順番 """ import dataclasses @dataclasses.dataclass class ...
490bfd37ebfa51bcf4eaf3019f0fdf6c542e5127
titoeb/python-desing-patterns
/python_design_patterns/bridge/ex.py
1,235
3.734375
4
from abc import ABC class Shape: def __init__(self, renderer): self.name = None self.renderer = renderer class Triangle(Shape): def __init__(self, renderer): super().__init__(renderer) self.name = "Triangle" def __str__(self): return self.renderer.render_triangle...
ccdf74f0435d63c7efe74177bcc8f34a4c7eae1b
anandshudda/dat-chapter-2
/numpy_practice.py
2,022
3.875
4
import pandas as pd import numpy as np # 1. Use arange to create an array of the numbers from 0 to 100. a = np.arange(101) print "Array of the numbers from 0 to 100: ", '\n', a, '\n' # 2. Create two arrays [1, 3, 5] and [2, 4, 6] and add them. x = [1, 3, 5] y = [2, 4, 6] z = np.add(x,y) print "Adding [1, 3, 5] and [...
f1576b68a38ea069cae3dbf808f9e4a37863e00c
LisandroGuerra/zombies1
/Lista3_desafio/questao05.py
70
3.59375
4
num = input("Entre com número inteiro positivo: ") print (num[::-1])
29e9a3e5f31badc37a0c7d00dd0a7c3dcad510b2
StylishSdp/ProgrammingTask
/Task2/栈/有效的括号.py
800
4
4
def isValid(s): if not s: return True if len(s) % 2 != 0: #通过一些明显的条件去掉一些False的例子 return False if s[0] == ')' or s[0] == ']' or s[0] == '}': return False if s[-1] == '(' or s[-1] == '[' or s[-1] == '{': return False stack = [] for i in range(len(s)): if...
fdcae381bf9aef293f664de508f1fe575bc250ce
simranmahindrakar/DAA-things
/gh - Copy.py
570
3.625
4
##def mystery(l): ## if len(l) < 2: #### return (l) ## else: ## return ([l[-1]] + mystery(l[1:-1]) + [l[0]]) runs = {"Test":{"Dhawan":[190,14,35,119],"Kohli":[3,103,13,42],"Pujara":[153,15,133,8]},"ODI":{"Dhawan":[37],"Kohli":[63]}} #runs["ODI"]["Pujara"].extend([44]) #runs["ODI"]["Pujara"].a...
4311e7c569bfb53fc8a127f9d56629f4a6671e35
Jack-Sh/04_Math_Quiz
/08_greater_lesser.py
1,363
4.15625
4
import random def choice_checker(question, valid_list, error): valid = False while not valid: # Ask user for choice (and put in lowercase) response = input(question).lower() # iterates through list and if response is an item # in the list (or the first letter of an item), the...
ecbd30291b872f1099f59a37326443259464e816
EmsDz/EmsDominoGame
/Clases/ClassHandPlay.py
3,472
3.640625
4
# class handPlay(object): # partida """docstring for handPlay""" def __init__(self, players): self.handPlayNumber = 0 # present hand play, is integer self.players = players # players in this round, is a list self.firstsTurn = '' # who play first self.openGameToken = '' #...
fff5cd69fc413a7bbd29ad8b5c76d9aff0b237b6
Zabdielsoto/Curso-Profesional-Python
/7.- Unidad/Ejercicio2.py
624
4.25
4
'''Ejercicio 2: Clases Modifique el método del ejercicio anterior para convertirlo en una propiedad (@property) ''' class Punto: def __init__(self, x, y): self.x = x self.y = y @property def cuadrante(self): if self.x > 0 and self.y > 0: print("Primer cuadrante") elif self.x < 0 and sel...
850796d4461986e2e29f34a882786e899a7bad8a
brucemin/repertory
/exercise05/3.py
776
3.75
4
Number = int(input('请输入一个三位数:')) #输出每一位上的数 a = int(Number/100) b = int((Number-100*a)//10) c = int(Number%10) #判断a,b,c大小,并按从大到小排列,再从小到大排列 if a>b and a>c and b>c: print(str(a) + str(b) + str(c)) print(str(c) + str(b) + str(a)) elif a>b and a>c and c>b: print(str(a) +str(c) +str(b)) print(str(b) + str(c) ...
f212ee7e13223eb60571b62499e56ceeef2d9bbd
Helton-Rubens/Python-3
/exercicios/exercicio037.py
780
3.9375
4
num = int(input('Digite um número inteiro: ')) print('+='*10) print('''\nEscolha uma das bases para conversão: [\033[1;34m1\033[m] Converter para \033[4;35mBINÁRIO\033[m [\033[1;34m2\033[m] Converter para \033[4;35mOCTAL\033[m [\033[1;34m3\033[m] Converter para \033[4;35mHEXADECIMAL\033[m\n''') opc = int(input('Sua op...
ef91a079fb73758417e844ab90c3575104c746cd
ludwigwittgenstein2/Algorithms-Python
/copyThird.py
988
3.828125
4
#!/bin/Python """ Logging in Python """ import logging def firstLog(): logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) logger.info('Start reading database') #read database here records = {'John':55, 'tom':66} logger.debug('Records:%s', reco...
32de8a183bb0b8f673d185544e8d83a2b9757e1e
jproddy/rosalind
/bioinformatics_stronghold/seto.py
1,263
3.84375
4
''' Introduction to Set Operations http://rosalind.info/problems/seto/ Given: A positive integer n (n≤20,000) and two subsets A and B of {1,2,…,n}. Return: Six sets: A∪B, A∩B, A−B, B−A, Ac, and Bc (where set complements are taken with respect to {1,2,…,n}). ''' filename = 'rosalind_seto.txt' def union(A, B): return...
fd4c8a3f8de296ae8df949979ffd8c3602b97369
wong2/PyOthello
/src/network.py
1,292
3.75
4
''' network.py This module defines class Server and Client. They are used in network games. ''' import socket, sys, os class Server: def __init__(self): self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) port = 5543 self.socket.bind(('', port)) self.socke...
6340c85c3136ea4615724301b87e5252fc67077e
klisostom/Python
/Projetos/decida_por_mim.py
938
3.59375
4
import random """ Objetivo: Crie um script que responda qualquer pergunta que for feita a ele. Recomendo ter uma base de possíveis respostas (10-20 ou mais). Ex: Será que devo sair de casa hoje? Seu script reponde: “Sim, vai lá!” """ conjunto_respostas = [ 'Sim, vai lá!', 'Não, é estranho!', 'Talvez dê c...
3bd64d83524d44d8229de0fc8be77de7f4c75201
vitthalpadwal/Python_Program
/hackerrank/python_sort.py
1,765
4.375
4
""" You are given a spreadsheet that contains a list of athletes and their details (such as age, height, weight and so on). You are required to sort the data based on the th attribute and print the final resulting table. Follow the example given below for better understanding. image Note that is indexed from to , ...
1c4f2dd4d21fbe5251870e40ad305a55e5f760b8
jugu/projecteuler
/20160112_euler003.py
497
3.765625
4
'''The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of a given number N?''' ''' number of test cases ''' import math Ts = raw_input('') T = int(Ts) caseN = list() for i in range(T): caseN.append(long(raw_input(''))) for N in caseN: x = 2 while N%x == 0: N = int(N...
efcc50989912ee5f4dc8e8569ce6be68e68d4010
Syyan7979/Kattis-Solutions-python-
/Python Kattis/Kattis124(drmmessages).py
479
3.75
4
import string alphabet = string.ascii_uppercase def message(someString): counter = 0 out = "" for i in someString: counter += alphabet.index(i) for i in someString: out += alphabet[(alphabet.index(i) + counter)%26] return out def conversion(A, B): out = "" for i in range(len(A)): out += alphabet[(alphabet....
5e113a23f68b740462a4d98cfbac6b6c233271aa
tchaitanya2288/pyproject01
/dictionaries methods/set_update.py
306
3.875
4
##6 Set Union with Mutation = a_set.update() # Syntax: a_set.update(an_iter) # Example: s = set([1, 2, 3, 4, 5]) s.update(set([5, 6, 7])) print(s) #Output : set([1, 2, 3, 4, 5, 6, 7]) ''' Mutates a_set to be the union of set a_set and the set of elements in iterable an_iter. Returns None. ''' ''
ac8c7716c9ed9da4842bb1afdacb7cbaa4f532f2
youinmelin/practice2020
/recurrence_03_maze.py
3,215
3.71875
4
from random import choice import sys sys.setrecursionlimit(3000) # set the maximum depth as 3000 # 0: wall, 1:road, 2:terminal, 3:wrong road, 4:passed road class Maze(): def __init__(self,maze_list): self.maze_list = maze_list self.currentx = 1 self.currenty = 1 self.stepx = 0 ...
b30707789ef8429c866ac0190ed2c0edcbe2725f
zuohd/python-excise
/python_project/turple.py
127
3.890625
4
tuple1 = (1,) print(tuple1) tuple2 = (2, 3, 4, 5, 6) print(tuple2[0]) print(tuple2[-1]) # tuple can not change :tuple2[0]=1
53cbd077e5f6f5da71d972e87223357fa8600dd0
C-CCM-TC1028-111-2113/homework-1-JennyAleContreras
/assignments/22DigitosPares/src/exercise.py
529
3.890625
4
def main(): #escribe tu código abajo de esta línea number = input('Dame un número: ') pair = int for i in range(0, 10): pair = 0 if int(number[0])%2 == 0: pair = pair + 1 if int(number[1])%2 == 0: pair = pair + 1 if int(number[2])%2 == 0: ...
072d3165615dcb15084e2f7dbc56ce6af3470317
hn-on-fire/Python
/Basic Projects/Arithmetic Formatter/arithmatic_formater.py
1,790
3.640625
4
def arithmetic_arranger(questions, answers=False): if len(questions) > 5: return 'Error: Too many problems.' print1, print2, print3, print4 = "", "", "", "" for inpNums in questions: nums = inpNums.split() if nums[1] != '+' and nums[1] != '-': return 'Error: Operator must...
be6333704328b9c7c85bc00ebd34f5080b078800
augustkx/defer-defaults
/defer_defaults/deferral.py
798
3.5
4
import inspect from functools import wraps deferred = object() # An implementation of the deferrable args wrapper suggested by Jonathon Fine def deferrable_args(func): """ Use this to decorate a function that you want to accept "defer" arguments, which will be overwritten by defaults. :param func: A fun...
30043b764335efa70034fe0d312166c8dcd3c3b8
kmurphy/coderdojo
/07-Monkey_Wars/code/Monkey_Wars.py
3,728
3.90625
4
import turtle import math import random screen = turtle.Screen() screen.setup (width=600, height=600, startx=0, starty=0) screen.setworldcoordinates(-300,-10,300,500) WINDOW_WIDTH = 25 FLOOR_HEIGHT = 40 bob = turtle.Turtle() # draws the city red = turtle.Turtle() # red player blue = turtle.Turtle() # blue...
15162c4c356ea7eb2439412d745c6c515903e684
afrayz29/python-lessons
/exercises/11-Your-First-If/app.py
249
3.890625
4
total = int(input('How much money do you have in your pocket\n')) # YOUR CODE HERE if total>100: print("give me your money!") elif total>50: print("buy me some coffee your cheap!") elif total<50: print("you are a poor guy, go away!")
71501d9ebfa06c33e9ea9c6343be65a5e1785578
Kostimo/IT2SCHOOL
/PythonLessons spring 2021/Week4/task3.py
162
3.625
4
A = [1,2,3,4,5,6,7,8,9,10] m = int(input("M: ")) print(A) def shift(lst, sh): x = len(lst) - (sh%len(lst)) return lst[x:] + lst[:x] print(shift(A, m))
cb9ef8e6c0a1e59a7b4b8ebcce88a6206de1c031
Ravitejagupta/Python
/lc-1315.py
1,207
3.53125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None from queue import deque class Solution: def sumEvenGrandparent(self, root: TreeNode) -> int: visited = set() if not root: retu...
f8985f583de1e83d9efe1ceb36142456edb9fac8
safat/pratice
/src/codeforces/A281.py
198
4
4
def capitalize(input): first_char = input[0] if 'a' <= first_char <= 'z': first_char = str(chr(ord(first_char) - 32)) return first_char + input[1:] print(capitalize(input()))
f8d64dbaef27baf1b79034d0009de8a7745568b9
deepakag5/Data-Structure-Algorithm-Analysis
/leetcode/binarytree_second_minimum.py
2,128
3.953125
4
# Time Complexity: O(N)+O(N) =O(N) , N is the total number of nodes in the given tree. # We visit each node exactly once during dfs and then scan through visited # Space Complexity: O(N)+O(N) = O(N), for info stored on stack and visited def findSecondMin(root): if root is None: return None # this is ...
d2dd1371d54bde7afad3259405e38f00b6894005
w22116972/leetcode_Ender
/520. Detect Capital/520.py
869
3.640625
4
class Solution(object): def detectCapitalUse(self, word): case1 = True case2 = True case3 = True lower_case = 'abcdefghijklmnopqrstuvwxyz' upper_case = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' if word[0] in upper_case: case2 = False for i in range(1, len(w...
9a7fc625754d5f87356d1c95d0440f1a5fed5247
nurarenke/study
/anagrams_diff_permutations.py
1,308
3.90625
4
'''Cracking the Coding interview, problem 1.3: Given two strings, write a method to decide if one is a permutation of the other. Whitespace and punctuation are significant and it is case sensitive. >>> sorted_anagram("nura", "arun") True >>> count_anagram("nura", "arun") True >>> sorted_anagram("Burger ", "Burger"...