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
1eb61779347687b166f28a48fb2a69747482c8fe
LuckyLub/crashcourse
/test_cc_20190305.py
2,316
4.3125
4
'''11-1. City, Country: Write a function that accepts two parameters: a city name and a country name. The function should return a single string of the form City, Country , such as Santiago, Chile . Store the function in a module called city _functions.py. Create a file called test_cities.py that tests the function you...
8eae1ea6dc7a91282d328660005d27f8da589a7a
GameWars/Chaos-Theory
/HW2/sec28.py
1,114
3.578125
4
""" Boloutare Doubeni Math 532H - Non Linear Dynamics and Chaos with Applications September 22, 2014 Strogatz Exercise 2.8.2 """ from __future__ import division import numpy as np import matplotlib.pyplot as plt import scipy.integrate as integrate #args for linspace xmin = 0. xmax = 10. xn = 32 tmin = xmin tmax = ...
2fe0362e1f5b92cbb813e11aeff5a07a9f932be0
1tux/project_euler
/problem012.py
1,622
3.84375
4
from math import sqrt def sieve2(n): nums = range(2, n) primes = [] cur_index = 2 for i in nums: if i == cur_index: primes.append(i) for j in xrange(2, ((len(nums)+1) / i) + 1): nums[i*j - 2] = i cur_index += 1 return nums ### algorithm: ### get all prime dividors: ### using modified version of s...
02c12be97b033fd193d3bbe8e37a135bc6897143
1tux/project_euler
/problem005.py
391
3.65625
4
def gcd(a,b): if not b: return a return gcd(b, a%b) s = 1 for i in xrange(20, 0, -1): if s % i != 0: s *= i / gcd(s, i) print s # ^ this algorithm is of O(n * log n) since gcd is log # another algorithm is using a sieve to get primes till N # then finding their exponent using log: log(N, p) # and multipyin...
372261fa5d67a06341a948cb18e8c20cefa82c99
gmatsabu/Password-checker
/tests/test_password_is_valid.py
1,136
3.546875
4
from password_checker.password_checker import Password import pytest Password = "TeBo55Hj" special_char = "$#@!*" #print(any(c.isupper() for c in Password)) #true # passs ="matdsA122$p" # checker = Password(passs) # def test_password_is_valid(): # assert checker.lowercase() == True #password = Password() def te...
c4a6190da0cdbfc05b981df0e3db311bc1ca8ec7
yashsf08/project-iNeuron
/Assignment2-python/program-one.py
481
4.1875
4
""" 1. Create the below pattern using nested for loop in Python. * * * * * * * * * * * * * * * * * * * * * * * * * """ from math import ceil def draw_pattern(data): upper_limit = ceil(data/2) print(upper_limit) lower_limit = 0 for i in range(upper_limit): print('*'*(i+1)) for i in range(...
07987cbf2c47dc49c90e4ed73f58f4dec5a455b7
yashsf08/project-iNeuron
/Assignment1-python/program-one.py
337
4.0625
4
""" 1. Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 (both included). The numbers obtained should be printed in a comma-separated sequence on a single line. """ result = [str(x) for x in range(2000,3001) if x%7 == 0 and x%5 !=0 ] print(', ...
e3ac3931549a683b038d2164223c0d63ffa7eb99
2065983Y/amazing_app
/amazingapp/algorithms/astar.py
3,574
3.5625
4
__author__ = 'yanev' from math import sqrt from operator import attrgetter class Node: x = 0 y = 0 f_score = 0 g_score = 0 walkable = True def __str__(self): return "[ " + str(self.x) + ", "+ str(self.y) + " " + str(self.walkable) + " ]" def heuristicScore(a, b): return sqrt(pow...
d9c21c56229d219d2d3e63c3e87997051fa7ac7d
vladskakun/TAQCPY
/tests/TestQuestion18.py
696
4.03125
4
""" 18. Perfect Square Patch Create a function that takes an integer and outputs an n x n square solely consisting of the integer n. Examples square_patch(3) ➞ [ [3, 3, 3], [3, 3, 3], [3, 3, 3] ] square_patch(5) ➞ [ [5, 5, 5, 5, 5], [5, 5, 5, 5, 5], [5, 5, 5, 5, 5], [5, 5, 5, 5, 5], [5, ...
251975745094bce828e72eb2571e38a470aae3a1
vladskakun/TAQCPY
/tests/TestQuestion12.py
595
4.125
4
""" 12. Concatenate Variable Number of Input Lists Create a function that concatenates n input lists, where n is variable. Examples concat([1, 2, 3], [4, 5], [6, 7]) ➞ [1, 2, 3, 4, 5, 6, 7] concat([1], [2], [3], [4], [5], [6], [7]) ➞ [1, 2, 3, 4, 5, 6, 7] concat([1, 2], [3, 4]) ➞ [1, 2, 3, 4] concat([4, 4,...
604eb41c794380ba4cc3b4542518b7246889f582
vladskakun/TAQCPY
/tests/TestQuestion19.py
918
4.5
4
""" 19. Oddish vs. Evenish Create a function that determines whether a number is Oddish or Evenish. A number is Oddish if the sum of all of its digits is odd, and a number is Evenish if the sum of all of its digits is even. If a number is Oddish, return "Oddish". Otherwise, return "Evenish". For example, oddish_or_e...
c86585ae6baf8cd8772c752f335e161ce6382f38
vladskakun/TAQCPY
/tests/TestQuestion24.py
753
4.15625
4
""" 24. Buggy Uppercase Counting In the Code tab is a function which is meant to return how many uppercase letters there are in a list of various words. Fix the list comprehension so that the code functions normally! Examples count_uppercase(['SOLO', 'hello', 'Tea', 'wHat']) ➞ 6 count_uppercase(['little', 'lower...
ead4321438bb76f87dea904a532ec6ee6f2a6d78
KozinOleg97/Lab_2_raspozn_BC
/RLE.py
2,414
3.53125
4
import numpy as np from PIL import Image, ImageDraw def image_to_grey(original_im, height, width): array_gray = np.zeros([height, width]) for row in range(height): for col in range(width): r = original_im[col, row][0] g = original_im[col, row][1] b = original_im[col...
86d75898a54e2fc32954be8747c54a1b27ec4182
toroleyson/data-prework
/1.-Python/1.-Snail-and-Well/Problem 1 - Arnoldo Leyson.py
813
3.9375
4
Python 3.6.8 (v3.6.8:3c6b436a57, Dec 24 2018, 02:04:31) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license()" for more information. >>> well_height = 125 >>> daily_distance = 30 >>> nightly_distance = 20 >>> snail_position = -125 >>> days = 0 >>> while snai...
bef9c39d7a11dbedc7633555a0b6c370384d737f
HakimZiani/Dijkstra-s-algorithm
/dijkstra.py
2,356
4.28125
4
#---------------------------------------------------------------------- # Implementation of the Dijkstra's Algorithm # This program requires no libraries like pandas, numpy... # and the graph DataStructure is a dictionary of dictionaries # # Created by [HakimZiani - zianianakim@gmail.com] #-----------------------------...
faa19462725653c83f971c0ca8717b085e16973d
eishk/Udacity-Data-Structures-and-Algorithms-Course
/P0/Task4.py
1,188
4.3125
4
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) calls_caller = set() calls_called = set() t...
8318d4a5b9e442193b267dd7e045f60adabfe243
ramendra-singh/Practice
/DataStructure/Strings/secondMostChar.py
1,400
4.1875
4
''' Program to find second most frequent character Given a string, find the second most frequent character in it. Expected time complexity is O(n) where n is the length of the input string. Examples: Input: str = "aabababa"; Output: Second most frequent character is 'b' Input: str = "geeksforgeeks"; Output: Second m...
234879a92fa817695fb653aa79da391cbb8b489d
ramendra-singh/Practice
/DataStructure/LinkedList/singleLinkedList.py
1,209
3.90625
4
class Node: def __init__(self, init_data): self.data = init_data self.next = None def set_next(self, new_next): self.next = new_next class UnOrderedList: def __init__(self): self.head = None def add(self, item): temp = Node(item) temp.set_next(self.head...
5008030847eba78d3da87a3a6c7b28cad6a553ab
Ratna-Sree/techbee
/Find.py
929
3.59375
4
#assignments - 14/09/19 #2)print all the names in the below data var=""" line 1 line 2 start deepa priya sandy end line 3 line4 start hema guru end line5 start krishna vivek end line6""" """ search_start_pos=0 # searching 'start' word from zero index search_end_pos=0 ...
6678e00ad91adc25ccfdf3c29a2f8dc096afb936
simple-nick/simple-calc
/main.py
195
3.84375
4
def add(num_1, num_2): output = num_1 + num_2 return output def subtract(num_1, num_2): output = num_1 - num_2 return output def multiply(): pass def divide(): pass
29791d166ecc57376e54f0ae83edebaae75acc2b
haema5/python_algorithms_and_structures
/hw07_01.py
932
4.125
4
# -*- coding: utf-8 -*- # 1. Отсортировать по убыванию методом «пузырька» одномерный целочисленный массив, # заданный случайными числами на промежутке [-100; 100). Вывести на экран исходный # и отсортированный массивы. from random import randint MIN = -100 MAX = 99 ARRAY_LEN = 10 def bubble_sort(array): n = 1 ...
5e3c9a4e69b4868312b22828c5bc949fc51101bb
haema5/python_algorithms_and_structures
/hw02_1.py
1,865
3.578125
4
# Написать программу, которая будет складывать, вычитать, умножать или делить два числа. # Числа и знак операции вводятся пользователем. После выполнения вычисления программа не должна # завершаться, а должна запрашивать новые данные для вычислений. Завершение программы должно # выполняться при вводе символа '0' в каче...
4602c515a991dbcd79c9b09569842846d9cad35f
haema5/python_algorithms_and_structures
/hw02_6.py
1,170
3.9375
4
# В программе генерируется случайное целое число от 0 до 100. Пользователь должен # его отгадать не более чем за 10 попыток. После каждой неудачной попытки должно # сообщаться больше или меньше введенное пользователем число, чем то, что загадано. # Если за 10 попыток число не отгадано, то вывести загаданное число. from...
be9b32579e460a7b44864ba89cd6161fbf03eff5
bmosc/Mindtree_TechFest_2015
/fractals/koch snow flake curve.py
879
4.125
4
#!/usr/bin/python from turtle import * def draw_fractal(length, angle, level, initial_state, target, replacement, target2, replacement2): state = initial_state for counter in range(level): state2 = '' for character in state: if character == target: state2 += replac...
ab5aa05f409fc0e0ff4f2e0deabaab116e5e74ca
johns/cmsi485
/homework1/Pathfinder.py
4,090
3.625
4
''' John Scott The Pathfinder class is responsible for finding a solution (i.e., a sequence of actions) that takes the agent from the initial state to all of the goals with optimal cost. This task is done in the solve method, as parameterized by a maze pathfinding problem, and is aided by the SearchTreeNode D...
ac68226a997c7c29a695f8a7f980010eeb5c2ae8
satyam4853/PythonProgram
/Functional-Programs/Quadratic.py
613
4.15625
4
""" * Author - Satyam Vaishnav * Date - 21-SEP-2021 * Time - 10:30 PM * Title - Quadratic """ #cmath module using to compute the math function for complex numbers import cmath #initalize the variables taking from UserInput. a=float(input("Enter the value of a: ")) b=float(input("Enter the value of b: ")...
057b7104f47d3b2501d57d7e5315294696a76fa9
iamish08/ML
/1&3.py
4,485
3.625
4
/////////////////////////1st Pgm/////////////////////////////////////////////////// import csv hypo = ['%','%','%','%','%','%'] csv_file = open('/home/niktwister/training_examples.csv') readcsv = csv.reader(csv_file,delimiter=',') data = [] print('The training examples are :') for row in readcsv: print(row) ...
55a9b42465f1851934b1f9b51734914234e16708
OnLinedPaper/sierpinski_simulator
/sierpinsky.py
1,284
3.96875
4
import numpy as np import pylab from random import randint #bit of a misnomer, but "midpoint" displaces towards the next point #at the user's requested strength. a dis of 0.5 results in the normal #fractal. higher values result in "tighter" fractals, lower values #result in the pattern becoming less distinct. def ...
a66020757880126238995819ac23c710ef6c6ec4
moneytech/code-2
/example/hiring/general/1-numeric-converter.py
2,192
3.703125
4
#!/usr/bin/env python ones = [ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen",...
38b86da9a5058294f5b4330b967da9118cf67393
ongaaron96/kattis-solutions
/python3/2_6-4thought.py
505
3.796875
4
def get_expression(n): operations = ['+', '-', '*', '//'] for op_one in operations: for op_two in operations: for op_three in operations: expression = f"4 {op_one} 4 {op_two} 4 {op_three} 4" if eval(expression) == n: return expression.replace("//", "/") return "" num_cases = i...
57c933a77052342184666e6a687b9120ae025138
ongaaron96/kattis-solutions
/python3/1_4-quickestimate.py
71
3.625
4
n = int(input()) for _ in range(n): num = input() print(len(num))
57f7952096a569b20888538584a2736fb65c9147
ongaaron96/kattis-solutions
/python3/1_4-oddmanout.py
309
3.5625
4
n = int(input()) for i in range(n): num_guests = int(input()) codes = input().split() current_codes = set() for code in codes: if code in current_codes: current_codes.remove(code) else: current_codes.add(code) odd = list(current_codes)[0] print(f"Case #{i + 1}: {odd}")
92af7e8525df3daf8adc29fc169c119dcc697b8b
ongaaron96/kattis-solutions
/python3/1_4-trik.py
328
3.875
4
def swap(arr, first, second): temp = arr[first] arr[first] = arr[second] arr[second] = temp moves = input() arr = [1, 0, 0] for c in moves: if c == 'A': swap(arr, 0, 1) elif c == 'B': swap(arr, 1, 2) else: swap(arr, 0, 2) for index, val in enumerate(arr): if val == 1: print(index + 1) ...
3a544b3714fb0b3b9b671c6cae5d661313abc11e
DrSquidX/Old-Projects
/Normal Scripts/school day calculator.py
438
3.984375
4
schoolday_nobreaks = int(input("How many weeks of school are there?: ")) holiday_weeks = int(input("How many weeks of holiday?: ")) holidays = int(input("How many days of holiday you have(excluding weekends)?: ")) schoolday_nobreaks = schoolday_nobreaks + holiday_weeks days_of_school_noholidays = schoolday_nobrea...
ee51bd717a68449175637aa76dd10cad28fc9a83
DrSquidX/Old-Projects
/Normal Scripts/Untitled-Adventure-Game.py
41,270
3.90625
4
#this is my first game in python. import time import random HP = 100 bow_ammo = 10 max_damage_taken = 50 min_damage_taken = 10 question_answered = False attack_damage = random.randint(10, 75) damage_taken = random.randint(min_damage_taken, max_damage_taken) play_game = input("Would You Like To Play This Game?(y/n): ") ...
b5b948abd14f97c5bc5ea0fb5025511f46f620eb
wokeupsleepy/csvsorter
/csvsorter/csvsorter.py
544
3.640625
4
import csv def listreader(listfile): freshset = [] with open(listfile) as csvfile: readlist = csv.reader(csvfile) for line in readlist: freshset.append(line[0]) return freshset #listcomparison method returns everything in a that is not in b def listcomparison(a,b): c = set(...
7bcb4e3e8ecd34096b6d933a2267bbeaceca3409
marcial2020/python_1
/if statement comparison.py
230
4.03125
4
def max_num(num1, num2, num3): if num1 >= num2 and num1 >= num3: return num1 elif num2 >= num1 and num2 >= num3: return num2 else: return num3 print("You're number is: " + str(max_num(3,20,5)))
35287ad6b8bc396fd392aa0383eae1acdef4e960
marcial2020/python_1
/reading files.py
401
3.9375
4
# r mean read # a means adding # w means overwrite everything in the file # r+ means modify the file employee_file = open("employee.txt","r") print(employee_file.readable()) print(" ") print(employee_file.read()) print(" ") print(employee_file.readline()) print(" ") print(employee_file.readlines()) print(" ") for em...
3f0be754908ceab1ebd7276f1211ca020bcee5a6
misgna/SCfT
/geezSpell.py
1,435
4.03125
4
''' GeezSpell is a spelling corrector for languages that use geez letters. It suggests words for a misspelt word without transliterating. ''' from lexicon import GeezWords from wordToGeez import WordToGeez from transliterate import Transliteration from spellingCorrector import SpellingCorrector #Step-1: L...
a0eda0689d8bd25cf0e626a53d10855f16dee22f
mlixytz/chess-ai
/board.py
5,298
3.53125
4
from tkinter import Tk, Canvas, PhotoImage, mainloop, Button, Label from common import * WIDTH, HEIGHT = 530, 580 start_x, start_y = 37, 39 space = 57 choice = 0 box_tag = 0 tk = Tk() canvas = Canvas(tk, width=WIDTH, height=HEIGHT) # 存储棋盘与棋子信息 board = [] # 存储棋盘与canvas tag信息 board_tag = [] photo_image_dict = {} d...
1788fb8544162d09ca6c8c1b02f6d5d5fc9610e5
aditbro/Seleksi-1-Asisten-LabPro-2018
/src/2-Problem05.py
517
3.734375
4
#Program mencari index nilai terkecil numKelompok = int(input('Masukan jumlah kelompok :')) minAnggota = None kelMin = None tempNumAnggota = None for i in range(numKelompok): tempNumAnggota = int(input('Masukan jumlah anggota kelompok {} :'.format(i + 1))) if(kelMin is None): kelMin = i + 1 minAnggota = t...
5bc1673c55301e31a33178ea6d9a7eb7d9da64e2
SKosztolanyi/Python-for-Data-Science
/Epidemology_Simulations/ps4.py
4,292
3.609375
4
# 6.00.2x Problem Set 4 import numpy import random import pylab from ps3b import * # # PROBLEM 1 # def simulationDelayedTreatment(numTrials): """ Runs simulations and make histograms for problem 1. Runs numTrials simulations to show the relationship between delayed treatment and patient outco...
dd3dcadcda9268d675beeefb7be001541b8a5a06
SKosztolanyi/Python-for-Data-Science
/Simple_Tasks/23_Monte_carlo_balls.py
1,023
4.09375
4
import random def drawing_without_replacement_sim(numTrials): ''' Runs numTrials trials of a Monte Carlo simulation of drawing 3 balls out of a bucket containing 4 red and 4 green balls. Balls are not replaced once drawn. Returns a float - the fraction of times 3 balls of the same colo...
ccd6ad44d7a15a319338f1744da384dd8b12b73f
raghavbhatnagar96/Python-Codes
/Class/area.py
297
3.765625
4
class Rectangle: def __inti__(self,l,b): self.l = l self.b = b def area(self): return point(self.x*self.y) def perimeter(self): return point(2*(self.x+self.y)) if __name__ == "__main__" p1 = point(1,3) p3 = p1.area() p4 = p1.perimeter() print "("+str(p3)+")" print "("+str(p4)+")"
10ed5f8ae42d642eba8c4640c3784a6f04f6bd9f
raghavbhatnagar96/Python-Codes
/HigherOrderFunctions/myfilter1.py
319
3.640625
4
def myreduce(f,l,initial): acc = initial for i in l: acc = f(acc,i) return acc def sum(l): return myreduce(lambda x,y:x+y,l,0) def mul(l): return myreduce(lambda x,y:x*y,l,1) def conc(l): return myreduce(lambda x,y:x+y,l,"") a = [1,2,3] b = ['a','r','m','i','t','h','a'] print sum(a) print mul(a) print conc(b)
46701b53f7736f387972d98dcb1441d614009430
raghavbhatnagar96/Python-Codes
/listsum.py
213
3.8125
4
n = input("Enter the number of numbers") a = [] count = 0 sum = 0 sum1 = 0 while count<n: num = input("Enter the number") a.append(num) count = count + 1 for i in a: for j in i: sum = sum + j j = j + 1
28a9ed74a7d161723f204bc606951bc4479a96dc
raghavbhatnagar96/Python-Codes
/fibonacci.py
85
3.734375
4
n = input("Enter the number") if(n==0): return 0 elif(n==1) return 1 else return
66ffd69fa02c0107bf4eda949da2cd4e4e651edf
sandypict/Python_programming
/zip.py
151
4.03125
4
# Parallel iteration names=['a','b','c'] ages=[1,2,3] print zip(names,ages) for n,a in zip(names,ages): print "{:>16} {:>5}".format(n,a)
87ba751d138820aa79a536121d8d2d1fdd803d78
sandypict/Python_programming
/word_count.py
649
3.703125
4
from pprint import pprint as pp def get_word_count(txt_file): word_count = dict() for line in open(txt_file): for word in line.rstrip().split(): word_count[word] = word_count.get(word,0)+1 return word_count def group_words_by_count(wc): group_by = dict() for wo...
6dca96d78b6334d95e4ad910c9cc30bde8ae63ad
sandypict/Python_programming
/functions.py
688
3.65625
4
from sys import argv print argv def power (x,n=0): return x*n print power(4,2) print power(4,4) print power(4) ''' def file_copy_mirrir(source=NA, dest=NA): if source==NA or dest==NA: print "Insufficinet arguments"" return else: for line in open(source): ''' # fu...
834943cca0f5061d16308127a6de6bfeb6633209
kennethhagist/math_OOP
/math.py
638
3.75
4
import Math class MathDojo(object): def __init__(self): self.result = 0 def add(self, *args): for i in args: if type(i) == list or type(i) == tuple: for k in i: self.result += k else: self.result += i return sel...
2c6536e36c175fde978191d7041a56f0320d8d15
WOWOStudio/Python_test
/Xin/game/maze_game/tortoise.py
1,531
4.1875
4
#小乌龟模型 from turtle import Turtle class Tortoise(Turtle): def __init__(self,maze_list,start_m,start_n,end_m,end_n): Turtle.__init__(self) self.maze_list = maze_list self.m = start_m self.n = start_n self.end_m = end_m self.end_n = end_n self.hideturtl...
400698a7c93384ffb2ba7c27e9b1b967368f198f
WOWOStudio/Python_test
/Xin/game/maze_game/maze.py
858
3.953125
4
#迷宫设定 from turtle import Turtle class Maze(Turtle): size = 20 def __init__(self,maze_list): Turtle.__init__(self) self.maze_list = maze_list self.hideturtle() self.speed(0) self.draw_walls() def draw_wall(self): self.pendown() self.begi...
2aa95f286b5a2254d56c58d9571efbc12f7824a7
WOWOStudio/Python_test
/Xin/LeetCode/data_structure/chapterI/sectionII.py
714
3.625
4
''' 剑指 Offer 05. 替换空格 请实现一个函数,把字符串 s 中的每个空格替换成"%20"。 示例 1: 输入:s = "We are happy." 输出:"We%20are%20happy." 限制: 0 <= s 的长度 <= 10000 作者:Krahets 链接:https://leetcode-cn.com/leetbook/read/illustration-of-algorithm/50ywkd/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 ''' class Solution: def ...
3c88abfeb44a20bba42464ec7cdbdfac594aeba2
ctokheim/deepDegron
/deepDegron/pvalue.py
1,025
3.53125
4
import numpy as np def cummin(x): """A python implementation of the cummin function in R""" for i in range(1, len(x)): if x[i-1] < x[i]: x[i] = x[i-1] return x def bh_fdr(pval): """A python implementation of the Benjamani-Hochberg FDR method. This code should always give preci...
50a46f683f9ef5da82e42de65a010968305c1ae2
BuglessCoder/algorithm-1
/Lintcode/intersection-of-two-arrays-ii.py
826
3.625
4
class Solution: # @param {int[]} nums1 an integer array # @param {int[]} nums2 an integer array # @return {int[]} an integer array def Solution(self): pass def intersection(self, nums1, nums2): # Write your code here nums3 = [] n1 = len(nums1) n2 = len(nums2) ...
aaa75089328793ba67b177882d5edf79a219eeb2
Mayym/learnPython
/2-Python高级语法/2-1模块、包、异常/6-9.py
708
3.828125
4
import random # random(): 获取0-1之间的随机小数 # 格式: random.random() # 返回值: 随机0-1之间的小数 print(random.random()) # 随机生成0-100之间的整数 print(int(random.random() * 100)) # choice(): 随机返回序列中的某个值 # 格式: random.choice(序列) # 返回值: 序列中的某个值 l = [str(i)+"haha" for i in range(10)] print(l) rst = random.choice(l) print(rst) # shuffle(): 随机打...
53b144754479685a088d7088de189b7f2e51cbc9
Mayym/learnPython
/1-OOP/14-3.py
549
3.609375
4
# 组装类例子 -3 from types import MethodType class A(): pass def say(self): print("Saying") a = A() a.say = MethodType(say, A) a.say() print(A.__dict__) help(MethodType) # 利用type造一个类 # 先定义类应该具有的成员函数 def say(self): print("Saying") def talk(self): print("Talking") # 用type来创建一个类 A = type("AName", (obje...
e2c667ae64facebd8546107afb9b1774a9576914
Mayym/learnPython
/1-OOP/03.py
1,772
4.21875
4
class Student(): name = "May" age = 20 def say(self): self.name = "zym" self.age = 22 print("My name is {0}.".format(self.name)) print("My age is {0}.".format(self.age)) def say_again(s): print("My name is {0}.".format(s.name)) print("My age is {0}.".for...
cd9456e32123ea9aeab55c04c6a03b315568714a
Mayym/learnPython
/2-Python高级语法/2-2 函数式编程/1-5.py
1,189
3.90625
4
# 装饰器 def hello(): print("Hello, world!") hello() f = hello f() # f和hello是一个函数 print(id(f)) print(id(hello)) print(f.__name__) print(hello.__name__) print('-' * 100) # 现在有新的需求:对hello功能进行扩展,每次打印hello之前打印当前系统时间 # 而实现这个功能又不能改变现有代码 # -->使用装饰器来完成 import time # 高阶函数,以函数作为参数 def print_time(f): def wrapper(*args...
1f20c7cb73d5c174a4a0de4094be3d4d88991bf8
Mayym/learnPython
/2-Python高级语法/2-2 函数式编程/1-2-1.py
609
3.90625
4
# map举例 # 有一个列表,想对列表里的每一个元素乘以10,并得到新的列表 l1 = [i for i in range(10)] print(l1) l2 = [] for i in l1: l2.append(i * 10) print(l2) print("-" * 100) # 利用map实现 def mul_ten(n): return n * 10 l3 = map(mul_ten, l1) # print(list(l3)) (一) # map类型是一个可迭代的结构,所以可以使用for遍历 ''' for i in l3: print(i) (二) ''' ...
6daa72f550b4d49b29b17b67a0d17685d9dac12e
Mayym/learnPython
/1-OOP/09-3.py
683
3.796875
4
# property class A(): def __init__(self): self.name = "may" self.age = 22 # 此功能,是对类变量进行读取操作的时候应该执行的函数功能 def fget(self): print("读取") return self.name # 模拟的是对变量进行写操作的时候执行的功能 def fset(self, name): print("写入") self.name = "名字:" + name # fdel模拟的是删除变量...
718c316d158ee210200001825575810492be946b
DiTellaGit/TP1
/TP1.py
1,539
3.6875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Apr 1 00:07:13 2019 @author: mat """ import sys def esPrimo(n): i = 2 esprimo= "si" while i <= n/2: if n % i == 0: esprimo= "no" break else: i += 1 return esprimo def ie...
0df6ee651a0d1a6bf3d363315a420fb73d928992
FabianRei/Euler
/10.py
609
3.671875
4
import numpy as np n = 2000000 def getPrimes(maxNumbers): primes = [] numbers = np.array(list(range(2, maxNumbers)), dtype=np.int64) for i in range(len(numbers)): n = numbers[i] if n == 0: continue primes.append(n) deletionIndexes = [] # smarter indexing...
31df2ee0f4a81347ff3778a3955fe5f8a25c3b56
FabianRei/Euler
/4.py
343
3.78125
4
import itertools digitNum = 3 def isPalindrome(num): return str(num) == str(num)[::-1] palindromes = [] mi = int('1'+ '0'*(digitNum-1)) ma = mi*10 nums = list(range(mi, ma)) combos = itertools.combinations(nums, 2) for x, y in combos: if isPalindrome(x*y): palindromes.append(x*y) print(palindromes) ...
51fb1d4841a48506db21c2ed6ec86fe03a08196a
axxsxbxx/SSAFY5-Algorithm
/week11_6_8/BOJ_1626_상민.py
485
3.609375
4
''' 아이디어 - 포켓몬을 dictionary에 저장한다. - 두 가지 방법 { 번호 : 포켓몬 } { 포켓몬 : 번호 } - dictionary는 in 연산자가 O(1) 시간밖에 걸리지 않기 때문에 빠를듯 ''' poketmon_dict = {} N, M = map(int, input().split()) for i in range(1, N + 1): poketmon = input() poketmon_dict[str(i)] = poketmon poketmon_dict[poketmon] = i for target in l...
96042c5f450cf80cb43a14de82e05a78705e9420
axxsxbxx/SSAFY5-Algorithm
/week6_4_20/PGR_3진법 뒤집기_상민.py
178
3.8125
4
def solution(n): ten_three = '' while n > 2: n, remainder = divmod(n, 3) ten_three += str(remainder) ten_three += str(n) return int(ten_three, 3)
0cd111dcebac9eef0bd2f2b7ba38d00a78b03240
luzonimrod/PythonProjects
/Lessons/MiddleEX8.py
725
3.875
4
#Write a Python program to get a single string from two given strings, #separated by a space and swap the first two characters of each string. #Sample String : 'abc', 'xyz' #Expected Result : 'xyc abz' Name=input("Enter two strings and sepreate them with space:") name2=Name.split(" ") name3=name2[0] name4=name2[1] siz...
3b24e2a04e23058ab07b84286471a9fcb5df678e
luzonimrod/PythonProjects
/Lessons/MiddleEX1.py
250
4.125
4
#Write a Python program to display the current date and time. Sample Output : #Current date and time : #14:34:14 2014-07-05 from datetime import date today=date.today() ti=today.strftime("%d/%m/%Y %H:%M:%S") print("current date and time :\n " + ti)
71492e25012118b9b91fd369b6f6be67b80e123c
rustamovazamat/aza
/azama2__exam.py
156
4.03125
4
string = "ask not what your country can do for you, ask what you can do for your country" longest_word = max(string.split(), key = len) print(longest_word)
48a0acf89c5bef820330de78fa1882c8c9f0bcee
Aleksei-Zaichenko/Intro-Python-II
/src/player.py
996
3.515625
4
# Write a class to hold player information, e.g. what room they are in # currently. class Player(): def __init__(self,name,current_room): self.name = name self.current_room = current_room self.items = [] def displayCurrentLocation(self): print(f'You are currently at: {self....
087aef0e3630218ba50ea0934cb7d956546f270b
maxinocencio/projetoIntegradorBomtchau
/bomtchau.py
51,783
3.71875
4
#Telas from tkinter import * import pygame #------------TELA 4------------- class PoemaBolha(Toplevel): #Tela escolha de conteudo def __init__(self, original): #Inserindo inicialização self.frame_original = original Toplevel.__init__(self) self.title('Poema Bolha') # Inseri...
224c22eab353a0d3b00a75edaf3973ed76f7d347
sarahmgreen88/python-challenge
/PyPoll/main.py
2,626
3.765625
4
# Election Results # ------------------------- # Total Votes: 3521001 # ------------------------- # Khan: 63.000% (2218231) # Correy: 20.000% (704200) # Li: 14.000% (492940) # O'Tooley: 3.000% (105630) # ------------------------- # Winner: Khan # ------------------------- #Import OS import os #I...
6e0e37fa7e464f3a2db564317cd7fac1ddbfd912
Ayushmanglani/competitive_coding
/leetcode/November/2_LinkedListInsertionSort.py
460
3.53125
4
class Solution: def insertionSortList(self, head): dummy = ListNode(-1) curr = head while curr: curr_next = curr.next prv, nxt = dummy, dummy.next while nxt: if nxt.val > curr.val: break prv = nxt nxt = nxt.n...
c5fda6cf2db3405e150cb2d266566cf34cd6c019
Ayushmanglani/competitive_coding
/leetcode/Feb_2021/3_HasCycle.py
518
3.640625
4
class Solution(object): def hasCycle(self, head): slow, fast = head, head while fast != None and fast.next != None: slow = slow.next fast = fast.next.next if slow == fast: return True return False class Solution(object): def ha...
7449f8eea904f21ab3347415808e4505ddd3d2b8
Ayushmanglani/competitive_coding
/leetcode/December/3_IncreasingOrderSearchTree.py
1,891
3.90625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def increasingBST(self, root): stack = [] if not root or not root.left and n...
015e65740d16b8c32bdf6f1ea1ddbd481fb6aeb4
Ayushmanglani/competitive_coding
/leetcode/September/22_MajorityElementII.py
294
3.53125
4
from collections import Counter class Solution: def majorityElement(self, nums: List[int]) -> List[int]: count = Counter(nums) n = len(nums) T = n//3 res = [] for i in count: if count[i]>T: res.append(i) return res
5472879519f5a550a673cb2f5a748000f9c58e2c
Ayushmanglani/competitive_coding
/DataStructures/Tree/HeightofBinaryTree.py
534
3.78125
4
class Node: def _init_(self,val): self.data = val self.left = None self.right = None # return the Height of the given Binary Tree def height(root): # code here if not root: return 0 global x x = [1] def traverse(i,root): if root: if i>x[0...
09dd714d2160e6a9ec594fcc632faf4c9e633727
Ayushmanglani/competitive_coding
/DataStructures/Tree/IdenticalTrees.py
1,077
3.8125
4
class Node: def _init_(self, data): self.right = None self.data = data self.left = None # your task is to complete this function # function should return true/false or 1/0 def isIdentical(root1, root2): global x x = [] if root1 == root2: return True if root1 and root...
09060157188555c95ab6489cfa3a6a89ad6dc5e1
Ayushmanglani/competitive_coding
/FAANG Roadmap/Week 3/GCDofTwo.py
495
3.5
4
for _ in range(int(input())): a,b = map(int, input().split()) def gcd(a,b): if (a == 0): return b if (b == 0): return a if (a == b): return a if (a > b): return gcd(a-b, b) return gcd(a, b-a) print(gcd(a,b)) fo...
3ceff99c4a3304e6779c2b8aa02ddfe5fa3d53ba
SMDaniyal/PIAIC
/Assignments/Assignment 2/Login-Signup Module/random/app.py
623
3.625
4
# import sqlite3 # print("\t\t\tLogin / Signup Module with mySQL ") # userInput = str(input("Enter Your Name: ")) # userPass = str(input("Enter Your Password: ")) # userCpass = str(input("Confirm Password: ")) # # def abc(): # # print("Hello") # # abc() # def func(userInput1,userPass1,userCpass1): # if ...
c1ff1b7ffb802c73387f7255db16f5f7eeb18989
bipinaghimire/lab4_continue
/set/thirtytwo.py
175
4
4
''' Write a Python program to remove an item from a set if it is present in the set. ''' s={1,3,5,7} a =int(input('enter an item from set to discard: ')) s.discard(a) print(s)
ecb807188b2d72b10e04ac8de99a4e878098cb62
bipinaghimire/lab4_continue
/dictionary/thirtyseven.py
193
4.125
4
''' Write a Python script to check if a given key already exists in a dictionary. ''' d={1:'apple', 5:'coconut', 2:'litchi', 4:'mango'} key= int(input('enter a key to check: ')) print(key in d)
8fe94488d3b80f71256e44bc648cc2ac4a4479fb
bipinaghimire/lab4_continue
/set/twentyeight.py
120
4.53125
5
''' Write a Python program to create a set ''' s = {5,2,6,3} print(s) X = set() print(f'Given set {X} is an empty set.')
7683518c723464172d103ab63ba4d1264c95ec4e
bipinaghimire/lab4_continue
/dictionary/fourtytwo.py
227
4.5625
5
''' .Write a Python program to iterate over dictionaries using for loops. ''' dict={1:'cow',2:'tiger',3:'lion',4:'monkey'} for i in dict: print(i) for j in dict.values(): print(j) for k in dict.items(): print(k)
08eb8591f55819150bd315d151ac90605c04a765
amoddhopavkar2/LeetCode-September-Challenge
/19_09.py
468
3.5
4
# Sequential Digits import collections class Solution: def sequentialDigits(self, low: int, high: int) -> List[int]: result = [] digits = collections.deque(range(1, 9)) while digits: num = digits.popleft() if num > high: continue if low <...
43d23131cd4274d8d0d08adc14262b3dfb2a142b
amoddhopavkar2/LeetCode-September-Challenge
/24_09.py
272
3.625
4
# Find the Difference from collections import Counter class Solution: def findTheDifference(self, s: str, t: str) -> str: counter_s = Counter(s) counter_t = Counter(t) for x in counter_t: if x not in counter_s or counter_t[x] != counter_s[x]: return str(x)
2ead0fb80cb1ea9cbc8efed49d01aef7c4bfb651
amoddhopavkar2/LeetCode-September-Challenge
/09_09.py
698
3.515625
4
# Compare Version Numbers class Solution: def compareVersion(self, version1: str, version2: str) -> int: list_ver_1 = version1.split(".") list_ver_2 = version2.split(".") x = abs(len(list_ver_1) - len(list_ver_2)) if len(list_ver_1) > len(list_ver_2): for _ in range(x):...
9da8f83eccbf20d3c84007c8839585b79b0b1df6
bartoszc/100-Python-challenging-exercises
/17.py
919
3.84375
4
"""Write a program that computes the net amount of a bank account based a transaction log from console input. The transaction log format is shown as following: D 100 W 200 D means deposit while W means withdrawal. Suppose the following input is supplied to the program: D 300 D 300 W 200 D 100 Then, the output...
b81177645e29c68ff42154dae02340fa60dcf865
dragonmsh/Biotech-CodonProject
/CodonProject.py
11,553
3.859375
4
# DNA sequence attributes. print("Input your DNA sequence below:") dnaSeq = input() print("Confirmation: Your DNA sequence is " + dnaSeq) print("Is this correct? Type yes or no.") correct = input() if correct == "yes": for j in range(len(dnaSeq)): if dnaSeq[j] == "A" or dnaSeq[j] == "T" or dnaSeq[j] == "G" ...
303de8b19a5abbf05ab10dcc0d04a3041f49c72b
mbwreath/mystery-word
/mystery_word.py
3,266
4.03125
4
import random #use import random print("Welcome to Mystery Game!!...Do you have what it takes, in less than 8 mistakes!!") a_file = ("/usr/share/dict/words") guesses=0 letters_guessed = [] guess_counter = 8 word = [] # easy_word_range = [>=4: <=6] # medium_word_range = [>6: <=10] # hard_word_range = [>10] def get_w...
81c90cd9daf0a32f3351c37314e71867a16f2221
sarahpcw/javaDateTime
/13 datetime 5 sikuli.py
1,273
3.703125
4
''' s m t w t f s 0 1 2 3 4 5 6 # 4-3=1 ; 5-3 = 2; 6-3=3 5Aug 6Aug 7Aug 8Aug 9Aug 10Aug 11Aug 12Aug # 0 + 3 + 1 = 4, the day I am on + 4 representing wed,thu,fri,sat # 1 + 3 + 1 = 5, # 2 + 3 + 1 = 6 ''' fro...
f8551faa26b591b1ee0d4325d236a87da3e5ad6e
imshawan/ProblemSolving-Hackerrank
/30Days-OfCode/Dictionaries and Maps.py
469
4.125
4
# Day 8: Dictionaries and Maps # Key-Value pair mappings using a Map or Dictionary data structure # Enter your code here. Read input from STDIN. Print output to STDOUT N=int(input()) phoneBook={} for _ in range(N): name,contact=input().split() phoneBook[name]=contact try: while(True): check=str...
2240dd5edf89fc32ff4edaa86e6132d3f1c93430
asnewton/ObjectOriented_Python
/class_varianble_&_specialMethod.py
1,079
3.875
4
class Employee: raise_amt = 1.04 #class variable def __init__(self, fname, lname, pay, company): self.fname = fname self.lname = lname self.pay = pay self.company = company self.email = fname + '.' + lname + '@' + company +'.com' def fullname(self): return ...
0e6a454bd206ee16df57c3f7f2981e7ebd284d89
hieutran106/leetcode-ht
/leetcode-python/easy/_206_reverse_linked_list/solution.py
472
4
4
from utils.my_list import ListNode class Solution: def reverseList(self, head: ListNode) -> ListNode: prev = None curr = head # process each list node until the end while curr: # store next node to a temporary variable temp = curr.next # point ba...
0121ce642b018f38da9075b16613b3ecd4acb8f5
hieutran106/leetcode-ht
/leetcode-python/hard/_410_split_array_largest_sum/test_solution.py
2,148
3.6875
4
import unittest from .solution import Solution class MyTestCase(unittest.TestCase): def setUp(self) -> None: self.s = Solution() def test_is_feasible1(self): nums = [1, 6, 4, 1, 2] m = 3 expects = {5: False, 6: False, 7: True, 8:True, 9: True, 10:True} for i in range(5...
68d4b708e24e54d71dca927123c8431836830a6a
hieutran106/leetcode-ht
/leetcode-python/easy/_1475_final_prices_discount/solution.py
976
3.6875
4
from typing import List import copy ''' Given the array prices where prices[i] is the price of the ith item in a shop. There is a special discount for items in the shop, if you buy the ith item, then you will receive a discount equivalent to prices[j] where j is the minimum index such that j > i and prices[j] <= pri...
067a3661846bdc3b7cae95c3bb643f784f0eb580
hieutran106/leetcode-ht
/leetcode-python/no_fail2/challenge_2i.py
980
3.59375
4
import sys def CountTriangles(A): n = len(A); A.sort(); count = 0; for i in range(n - 1, 0, -1): l = 0; r = i - 1; while (l < r): if (A[l] + A[r] > A[i]): # If it is possible with a[l], a[r] # and a[i] then it is also possible ...
f50e3c9833bd2b9664145fca58b302451ec4e7f0
hieutran106/leetcode-ht
/leetcode-python/medium/_15_3_sum/solution.py
1,075
3.65625
4
from typing import List class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: # sort the input array to eliminate duplicate answer nums = sorted(nums) n = len(nums) result = [] for i in range(n -2): if i >= 1 and nums[i-1] == nums[i]: ...
b6765b5614583d122a86cc5ef3d6cb29bb34ca7e
hieutran106/leetcode-ht
/leetcode-python/medium/_200_number_islands/solution2.py
934
3.5
4
from typing import List, Tuple class Solution: def numIslands(self, grid: List[List[int]]) -> int: numIslands = 0 rows = len(grid) cols = len(grid[0]) for i in range(rows): for j in range(cols): if grid[i][j] == "1": numIslands += 1 ...