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
173d26b6d3aeeed923e7ea5610104d33166b68c9
BradleyPelton/Leetcode-Solutions
/contests2019/leetcode20190817/wordsformed.py
883
3.5
4
from collections import Counter class contests2020q4.leetcode20201017.Solution: def countCharacters(self, words: List[str], chars: str) -> int: charCounter = list(Counter(chars)) print(charCounter) for word in words: wordCounter = list(Counter(word)) print(wordCount...
823d26227a64c592380418c28eb52a03593b15dc
irenecheco/python-lab1
/lab01.2.py
147
4.125
4
print("Inserisci una stringa: ") str = input() if(len(str)<2): print(" ") else: print(str[0] + str[1] + str[len(str)-2] + str[len(str)-1])
2136027a4d044643f8ba67a69088a97477654a41
dchartor/hackerrank
/counting_sort.py
178
3.875
4
def counting_sort(arr): result = [0 for x in range(len(arr))] for i in arr: result[i] += 1 return result arr = [1, 1, 3, 2, 1] print(counting_sort(arr))
e179c2421597f5dcb1c7eea8997cc051795b6fea
dchartor/hackerrank
/apple_and_orange.py
262
3.75
4
def countApplesAndOranges(s, t, a, b, apples, oranges): house = range(s, t + 1) apples = [x + a for x in apples] oranges = [x + b for x in oranges] print(len([x for x in apples if x in house]), len([x for x in oranges if x in house]), sep='\n')
cad58fbd8267c0903237616098ccb501329a0f49
pbridges1/prg105-Chapter-9-exercise-7-
/Chapter 9 exercise 7.py
553
4.03125
4
def is_triple(word): i = 0 count = 0 while i < len(word)-1: if word[i] == word[i+1]: count = (count + 1) if count == 3: return True i = (i + 2) else: count = 0 i = (i + 1) return False def find...
5430419491f1b4877fccbb4006a2cdc96c320301
chanul13/hubbard_dimer
/dmrg101/core/wavefunction.py
6,779
3.765625
4
# # File: wavefunction.py # Author: Ivan Gonzalez # """ A module for the wavefunctions. """ from math import sqrt import numpy as np from dmrg_exceptions import DMRGException from braket import braket def create_empty_like(wf): """Creates an new wavefunction empty but like the argument. You use this function...
0c5a683640f32c5c131c41ce5771ff9ed65457d2
muskanali-2001/most_frequency
/most_frequent.py
410
3.71875
4
def most_frequent(string): d = dict() for key in string: if key not in d: d[key] = 1 else: d[key] += 1 return d dict1=most_frequent('Mississippi') sorted_values = sorted(dict1.values()) sorted_dict = {} for i in sorted_values: for k in dict1.keys(): if d...
190ae18bda56583321a910d14d002582d2fd0b40
jeisson-Tellez/ciclo_1
/Unidad_iteraciones/ejecicios_unidad.py
4,964
4.125
4
#____________________________Ejercicio 1__________________________________________________ #Escribir un programa que solicite ingresar 10 notas de alumnos y nos informe cuántos #tienen notas mayores o iguales a 7 y cuántos menores # print("escriba sus 10 nota por favor :") # cantidad = 1 # contadorMayor = 0 # contad...
b3927ec9ca9d2e49445e7ef61d4c2cedbe140c7b
brpat07/parallel_programming
/example/ex_multiprocessing.py
777
4
4
# example of multiprocessing (this is the example of the non shared memory between parent and child process) # creating separate processes for each task import time import multiprocessing def square_num(num_array): for num in num_array: print ("square of " + str(num) + " is : " + str(num*num)) return ...
4aefc849d163d52c09719d1452dbb0ed9208269e
mariams27/coding-practise
/ctci/ArraysStrings.py
4,483
4.09375
4
from collections import defaultdict as dd ''' 1.1 Is Unique: Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures? Hints: #44, #7 7 7, #732 ''' # TODO: potential bit array solution to come back and try to implement # TODO: implement an inplace so...
53da6db2d977f16965669857d1604a73558bde20
dy-fi/Coding-Challenges
/euler/prime_factors/prime_factors.py
415
3.984375
4
import math def largest_prime_factor(n): maxi = -1 # reduce n while(n % 2 == 0): maxi = 2 n /= 2 # search through possible primes, reducing n as we find factors for i in range(3, int(math.sqrt(n) + 1), 2): while n % i == 0: maxi = i n = n / i ...
c18b78906551ce05e94764f95d7c8927c9afaea3
dy-fi/Coding-Challenges
/leetcode/add_two_numbers.py
1,082
3.96875
4
# You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. # You may assume the two numbers do not contain any leading zero, except the number 0 itself. #...
b32a498930d2701520f45965a56d65fa09e533ad
SergioG84/Python
/weight_converter.py
1,113
4.15625
4
from tkinter import * window = Tk() # define function for conversion def convert_from_kg(): grams = float(entry_value.get()) * 1000 pounds = float(entry_value.get()) * 2.20462 ounces = float(entry_value.get()) * 35.274 text1.insert(END, grams) text2.insert(END, pounds) text3.inser...
f005f1762afe26f9f654f8619d8b161a15293f71
star574/python-po-test
/Clean.py
573
3.765625
4
import os def del_file(path): for i in os.listdir(path): path_file = os.path.join(path, i) # 获取文件绝对路径 if os.path.isfile(path_file): os.remove(path_file) else: del_file(path_file) def Clean(): flag = input('是否清理以前的数据,y:确认,任意键取消\n:') if flag == 'Y' or flag =...
1bdb9e04d555b004cfbde35b959ed540da56d37c
Korimse/Programmers_Practice
/level1/K.py
220
3.5
4
def solution(array, commands): answer = [] for i in range(len(commands)): start, end, k = commands[i] ans = array[start-1:end] ans.sort() answer.append(ans[k-1]) return answer
04b9e2a82aa79e2aaba97531d8cb36e21ccc1983
MHSalehi/Programming
/Lecture1Repeat_Strings.py
2,130
4.28125
4
#Introduction, Printing Strings print ("Hello, Python!") spch = "Greetings!" print (spch + " What is your name?") #Class Task 1 print ("\n") g = 14 t = 0.12 tg = g+g*t print ("£ " + str(tg)) #Class Task 2 print ("\n") fg = 20 s = 0.4 #Calculate sale price to 2 d.p. sg = '{:.2f}'.format(fg-fg*s) print ("£ " + str(sg)...
6cdd0c87a8ef28f80649a87a89712a2c1557078e
jetpham/MangaFormating
/test.py
428
3.703125
4
import re def sorted_nicely(list): convert = lambda text: int(text) if text.isdigit() else text alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)] return sorted(list, key=alphanum_key) list = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg', '7.jpg', '8.jpg', '9.5.jpg', '9.jpg']...
44766f711aba83ad7d33dd6333feb6ef2802be93
noderod/TyHack
/Usbik_DB_HH.py
4,098
4
4
""" BASICS User gives an address where the bike station is, and then removes one of such from the bike database. Then, it adds the encrypted user information to the file. Every user needs to input a payment information mechanism, which is encrypted using their password as a key. Ecah line of the database contains the ...
9b30636a4de65f7c09d350e1eda5f16c5f3e5c15
NilanjanaLodh/alienInvasionGame
/ship.py
1,200
3.625
4
import pygame class Ship(): def __init__(self, screen, step=1): """Initialize , and set starting position""" self.screen = screen self.image = pygame.image.load('images/spaceship.bmp') self.rect = self.image.get_rect() self.screen_rect = screen.get_rect() self.rect...
68c7e672c0f8193584b960dce98800390b3a83f0
michalodehnal5/2048
/src/game.py
5,764
3.5625
4
#!/usr/bin/env python3 from src.constants import * import pygame import random class Game2048: def __init__(self): self.size = GAME_SIZE self.structure = [[0 for x in range(self.size)] for y in range(self.size)] def __str__(self): result = "" for y in range(self.size): ...
02b0d355297a05752f11a1f18b81e542b849ed01
Zyjqlzy/PythonStudyNotes
/Algorithm/select_sort.py
808
4.25
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 选择排序 """ def create_list(): user_input = input("请输入数据,逗号分隔:\n").strip() user_list = [int(n) for n in user_input.split(',')] print(user_list) return user_list def find_smallest_item(lst): smallest_item = lst[0] smallest_index = 0 for i in ...
32ed62b3bf84b6e5b876d5286133f193888fff15
MasterShu/Better-Python
/first/queueHistory.py
1,020
3.59375
4
import shelve from collections import deque from random import randint q = deque([], 5) q.append(1) q.append(2) q.append(3) q.append(4) q.append(5) # q已经满了, 当继续 append 时,最先进入的就出被移除队列 q.append(6) # 做一个简单功能的历史记录 sNumber = randint(0, 100) history = deque([], 6) historyFile = 'D:\\python\\learnPython\\res\\history' ...
550d4d6154ceb2a7e9a74329eb1bc3c01af6ea85
tanktoptony/ATBS
/subMethod.py
883
3.578125
4
import re namesRegex = re.compile(r'Agent \w+') print(namesRegex.findall('Agent Alice gave the secret documents to Agent Bob.')) # substitution method print(namesRegex.sub('REDACTED', 'Agent Alice gave the secret documents to Agent Bob.')) # Using \1 \2 \3 to sub groups 1 2 and 3 in the regex p...
852b02999e62885ce37ec85644b31777fc5b2b21
Himk47/python
/max min.py
253
4.09375
4
def maxmin(list): l = list[0] s = list[0] for num in list: if num > l: l = num elif num < s: s = num print("largest number=", l, "smallest number=", s) maxmin([1,2,3,4,5,6,7,8,9,10])
0f5698de78b19d4a2e86e59aa0d14d8065f3bbbb
Himk47/python
/decimal to binary.py
124
4
4
num=int(input("enter the number ")) bin=str(num%2) while num!=1: num=num//2 bin = str(num % 2) + bin print(bin)
2b8db2b48303fc002f0a43f0aec928035a79c6d2
Himk47/python
/filter +ve number.py
219
3.875
4
lst = [] n = int(input("enter the number: ")) for x in range(n): lst.append(input("enter the digits one by one: ")) print(lst) lst1 = [] for z in lst: if int(z) > 0: lst1.append(z) print(lst1)
d809eaaa7f5e2fd41750f49f1cabdac52c21219e
Himk47/python
/sum of two numbers.py
86
3.5
4
def sums(a,b): return (a==b) or (abs(a+b)==5) or (abs(a-b)==5) print (sums(8,3))
e90a7e84000a793bca0a861ea98ae141893e3ba6
Himk47/python
/exersice 2/DIFFERENT NUMBER.py
273
4.03125
4
def numbers(values): for i in range(len(values)): for j in range(len(values)): if values[i]==values[j] and j>i: print ("values are equal") return print ("values are not equal") numbers([1, 2, 3, 5, 5, 6])
737677590905dc5f74f67a637453ae373feca763
mathematicalmichael/spellfix
/make_names.py
3,216
3.890625
4
from faker import Factory import random faker = Factory.create() # probability of typo prob = 0.2 def delete_char(name): """ Remove a character at random from the string Parameters --- str name: string to remove a character from Returns: str name: perturbed string """...
42d729677ca5e6113af7fd7c7a908ccd041c450c
nlillie17/steganography
/green_screen.py
3,835
3.90625
4
# ## Problem 3: green-screening! # # This question asks you to write one function that takes in two images: # + orig_image (the green-screened image) # + new_bg_image (the new background image) # # It also takes in a 2-tuple (corner = (0,0)) to indicate where to place the upper-left # corner of orig_image rela...
570dbffb3c55724e8ad5d273226c92912c4a8f0a
wangfuli217/study_room
/algorithm/pair_of_prime_number.py
1,302
3.75
4
''' test test ''' import sys def is_prime_no( n ): if n % 2 == 0: return 0 else: for i in range(2,(n>>1)+1): if n % i == 0: return 0 return 1 def swap_v(l, i1, i2): tmp = l[i1] l[i1] = l[i2] l[i2] = tmp def is_prime_pair_list(l, s, depth): ...
08b7c11123ca983260bcb40b84b8822c02491a35
ISE2012/ch8
/CheckNum.py
270
3.578125
4
# -*- coding: utf-8 -*- """ Created on Wed Nov 11 02:45:59 2020 @author: ucobiz """ class CheckNum: """Return True if x is even""" def isEven(self,x): if(x%2 == 0): return True else: return False
e8b84f5f87ce171e8cebe4692305e9b5a95c6765
meiningerj/QRBCComputing
/Level1/Level1.py
249
3.65625
4
#!/usr/bin/env python import sys if len(sys.argv) != 2: print "Incorrect number of command line arguments." print "Usage: python file.py <arg1>" exit(1) var1 = int(sys.argv[1]) if var1 == 4: print "correct the key is " + str(hash("Level1"))
8aece43ba3fef62e3bd9b1f2cead27608995c2c4
SHASHANKPAL301/Rock-Paper-and-Scissor-game
/game.py
1,311
4.25
4
import random print(''' Welcome to the Rock,Paper and Scissor game. THe rule of the game is shown below:- 1. rock vs scissor---> rock win 2. scissor vs paper---> scissor win 3. paper vs rock---> paper win''') def game(computer, player): if computer == player: return None #tie elif comput...
990c2ff9ed4648d7dc0691a69d96e4efee896648
Helaa/projet-kolkata-plaid-parliament-of-ai
/kolkata-restaurant/Team.py
2,138
3.71875
4
from AdaptedPlayer import AdaptedPlayer from Strategies import * class Team: """ Team of AdaptedPlayers, useful for comparing 2 or more strategies. """ def __init__(self, *args, **kwargs): """ The players in the team must have the same strategy. """ if len(args)...
01659028312a186a7dddbc62c2ac13ca70803841
lee-taekgyu/2020-07-29-py
/exercise3-01.py
671
3.5
4
import sys import json count ={} def count_base(file_name): with open(file_name, 'r') as handle: for line in handle: if line.startswith('>'): continue line = line.strip() for s in line: if s in count: count[s] += 1 ...
cc3f967513afe5f4869b7796119281ceff090a57
iPROGRAMMER007/Pattern
/Test2.py
1,031
3.90625
4
def deposit(): money = int(input("Enter deposit amount : ")) print("Amount deposited : ", money) initBalance = initBalance + money print("Total account balance = ", initBalance) def withdraw(): money = int(input("Enter withdraw amount : ")) print("Amount withdrawl : ", money) ...
a8e20978dbde39524c5b424ae047f3f6e6139f65
elobejko/python-tutorial
/Task2.py
184
3.625
4
counts = dict() names = ['csew', 'cwen', 'csew', 'zqian','cwen'] for name in names: if name not in counts: counts[name] = 1 else: counts[name]+=1 print(counts)
6b6838926c56af0abec5d45f05c62248879d60bd
Tur-4000/python-project-lvl1
/brain_games/games/even_game.py
724
3.828125
4
"""Even Game.""" from random import randint import prompt from brain_games.game import run_game def even_game(): """Play Even Game.""" instruction = 'Answer "yes" if the number is even, otherwise answer "no".' run_game(get_game_data, instruction) def get_game_data(): """ Prepare game data. ...
3175f12873c083f6d69078b3cb0f3800148b2e7e
Tur-4000/python-project-lvl1
/brain_games/games/gcd_game.py
868
3.78125
4
"""GCD Game.""" from math import gcd from random import randint import prompt from brain_games.game import run_game MAX_PERIOD = 100 def gcd_game(): """Play GCD Game.""" instruction = 'Find the greatest common divisor of given numbers.' run_game(get_game_data, instruction) def get_game_data(): ""...
d91b45565235a978396f9e1da8e2d1e3a598a10b
GeminiAspros/LeetCode-Python
/Python/design-linked-list.py
2,130
3.578125
4
class Node(): def __init__(self, val, next_node): self.val = val self.next_node = next_node class MyLinkedList(object): def __init__(self): self.head = None self.length = 0 def get(self, index): if self.length == 0: return -1 if (index+1)> self...
d33961c4e745890c77c03f72d54ea2b1dd26a6db
maathi/cryptohack
/Hex/hex.py
185
4.09375
4
hex_string = input("enter your hex string: \n") str = "" for i in range(0, len(hex_string), 2): hex = hex_string[i:i+2] dec = int(hex, 16) char = chr(dec) str += char print(str)
5c696c273200fbcc450d4da0dcd622c6bcd8d3de
rabia-koc/OPENCV_2
/OPENCV__2/görüntü_yeniden_boyutlandırma.py
806
3.59375
4
import cv2 img = cv2.imread("1.jpeg") print(img.shape) # res = cv2.resize(img, (300, 300)) # yeniden boyutlandırma # küçültme işlemi yaptık res = cv2.resize(img, None, fx = 0.5, fy = 0.5) # 2'sinede 1 yazarsak resim aynı kalır. # küçültme büyültme işlemi yaptığımızda orjinallerdeki piksellere ne oluyor? # büyült...
65652102d22e58499be2e02aa6d53b22a07c965d
shaofen06/password-retry
/password-retry.py
433
3.9375
4
#password = 'a123456' #請使用者重複輸入密碼 #最多三次 #正確的話,就印出登入成功 #錯誤的話,'印出密碼錯誤!還有_次機會! password = 'a123456' x = 3 #總次數 while True: pwd = input ('請輸入密碼:') if pwd == password: print('登入成功!') break else: x = x - 1 print('密碼錯誤!還有', x ,'次機會!') if x == 0: break
c3f6ec6d42a0654aed417045691636bc1647416c
HuDunYu/031902106
/test.py
836
3.609375
4
import unittest from function import edit_text, count_keyword, count_switch, count_if_else with open("c.txt") as file_object: read_lines = file_object.readlines() lines = edit_text(read_lines) class MyTestCase(unittest.TestCase): def test_something1(self): total_num = count_keyword(lines) sel...
e366875e3d10d681ceb516286cb116f37c7ba08e
volodumurgaydayenko/sample
/Modul_3/lab_1.py
3,427
3.578125
4
import os # def max_int(a, b): # if isinstance(a,(int, float)) and isinstance(b,(int, float)): # if a > b: # return print(a) # elif b > a: # return print(b) # else: # return print(a) # else: # return print('Exeption') # # # max_int('vrvr', 5)...
5ea97ef45dcda8dd703e48f3887734dafa08f72d
chaithra-s/321810304038-Assignment-10
/unit 4 assignment 2.py
1,676
3.953125
4
#python progran to print in place multiples of 3 as Fuzz and multiples of 5 as "Buzz" and multiples of both as "Fuzzbuzz" for i in range(1,101): if i%3==0 and i%5==0: print("FizzBuzz") elif i%3==0: print("Fizz") elif i%5==0: print("Buzz") else: print(i) #program to remove consecutive duplicates from list ...
350d99da256ccce841ea0253a49046bdd296f78c
osuuster/CopyCat
/copycat.py
1,243
3.59375
4
import time import threading class C: def __init__(self): self.captured_input = () self.captured_time = () def capture_input(self): new_input = [] time_input = [] starting_time = time.time() capturing = True while capturing: user_input = inp...
3c14bae4419bbbbc78f4a924f93b19acaf906a5a
kjb4494/python_tester
/thread_test_code.py
1,193
3.75
4
from threading import Thread, Lock class ThreadTester: def __init__(self): self.lock = Lock() self._value = 0 def value_add_with_lock(self, num): for _ in range(num): with self.lock: self._value += 1 def value_sub_with_lock(self, num): for _ in...
d735b93b4abf7f93547e8ce6d4f9378ae0a640f7
sandeepmnani/Hangman
/Topics/String formatting/Film/main.py
156
3.859375
4
# Read input from user film_name = input() director = input() year_rel = input() print("{} (dir. {}) came out in {}".format(film_name, director, year_rel))
b007d102564e5879dc4dd74005d0edbe3c445adb
Okswwen/python_proj
/file_op.py
170
3.53125
4
# 将小说的人物书写到txt中 file1 = open('name.txt', mode='w') file1.write('诸葛亮') file1.close() file2 = open('name.txt') print(file2.read()) file2.close()
fd3b6f12d95aecfee5889f8752e3fa794c49fc0d
Okswwen/python_proj
/chinese_zodiac.py
480
3.765625
4
# 记录生肖,根据输入年份判断生肖 chinese_zodiac = '鼠牛虎兔龙蛇马羊猴鸡狗猪' # chinese_zodiac[4] # print(chinese_zodiac[0:4]) year = 2018 num = year % 12 print(num) print(chinese_zodiac[num]) # 在序列中 in 不在序列中 not in # 字符串拼接 + # 字符串多次重复 * num num 重复的次数 # 字符串切片 :[:] print('狗' in chinese_zodiac) print('狗' not in chinese_zodiac) print(chinese_zod...
3b5dba05b701c529db84fe6d6a12b6a4b539c79e
prsolans/ffai-v3
/sources/archive/source_teams.py
1,595
3.640625
4
# Original code used to create table of NFL teams import csv from bs4 import BeautifulSoup from utilities.utility_scrape import simple_get def get_team_data(): try: """## Enter the URL we are looking to crawl """ raw_html = simple_get('https://www.spotrac.com/nfl/') html = Beauti...
75cf24d118be26906003b6c7b521e74a3799a8aa
Soarnsky/advent2017
/2/advent_day2_1.py
469
3.59375
4
#!/usr/bin/python import sys with open("input.txt", "r") as f: spreadsheet = f.readlines() spreadsheet = [x.strip() for x in spreadsheet] sum = 0 for row in spreadsheet: numbers = row.split() lowest = highest = int(numbers[0]) for num in numbers: val = int(num) if val > highest: ...
7e32d341bb457e008ac14f66e4d1d4b7df9de900
juderzzo/works
/fall/18_db-nmcrnch/stu_mean.py
1,921
3.859375
4
#Calvin Chu #SoftDev #Average #Oct 2019 import sqlite3 #enable control of an sqlite database import csv #facilitate CSV I/O DB_FILE="discobandit.db" db = sqlite3.connect(DB_FILE) #open if file exists, otherwise create c = db.cursor() #facilitate db ops #=======================================...
12ecaeb48083e9580c066ddb0907ef35965eb36b
Iliya-Yadegari/Birthdate-project
/al_IliyaYadegari.py
2,899
4.03125
4
#!/usr/bin/env python3 ''' Author: "Iliya Yadegari" The python code in this file (a1_IliyaYadegari.py) is original work written by "Iliya Yadegari". No code in this file is copied from any other source except those provided by the teacher, including any person, textbook, or on-line resource. I have not shared this py...
85266495acce5bb298179d618369b84210b1a808
t871/python-challenge
/PyBank/main.py
1,846
3.953125
4
#Your task is to create a Python script that analyzes the records to calculate each of the following: #Import dependencies import os import csv months = [] total = [] profit = [] difference = [] greatest_increase = [] greatest_decrease = [] with open ('budget_data.csv','r') as f: reader = csv.DictReader(f, del...
c9d09061ece72e2b410abbe3f5acefea81f6f81b
pothie/ProjectEuler
/P10: Sum of Primes.py
687
3.8125
4
''' The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million(2*10^6). ''' # Input n: upper bound of the sum # Create a boolean list (0,1 list) a to indicate whether the index is prime # Store sum of primes below n in list s t = int(input().strip()) limit = 2*10**6+1 s =...
423189e2b6cf6c4de3f4a508f19edd7d9c4452b6
rochak12/classes
/Python/BST.py
1,398
3.90625
4
class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None class BST(object): def __init__(self, root): self.root = Node(root) def insert(self, new_val): self.insert_help(self.root, new_val) def search(self, find_val):...
a43a0d590b70294442e9d92916cad822be961d3e
ohlemacher/pychallenge
/3_equality/equality.py
2,339
4.34375
4
#!/usr/bin/env python ''' Find lower case characters surrounded by exactly three upper case characters on each side. ''' import pprint import re import unittest def file_to_string(): '''Read the file into a string.''' strg = '' with open('equality.txt', 'r') as infile: for line in infile: ...
4f261d3c978d51df826e8ff5543e98734e46243b
dongdong-2009/smaple
/算法/QuickFindUF.py
528
3.578125
4
class QuickFindUF(object): def __init__(self,N): self.N = N self.arr = range(int(N)) def union(self,p,q): if self.arr[p] > self.arr[q]: new_value = self.arr[q] old_value = self.arr[p] else: new_value = self.arr[p] old_value =...
3f02a48ee7265a81b5c71ca467077d043116e425
hanhaohh/datastruct
/linklist/LinkedQueue.py
1,009
3.6875
4
class LinkeQueue: class _Node: def __init__(self,value,next_ele=None): self._value = value self._next = next_ele def __init__(self): self.head = None self.tail = None self.size = 0 def get_size(self): return self.size def is_empty(self): ...
ee05faf9992dcd4041a0cacc10844f0e8f7ba000
fhossain75/CS103-UAB
/lab/lab08/lab08_19fa103.py
2,296
4.40625
4
# 19fa103; john k johnstone; jkj at uab dot edu; mit license # lab08 on recursion # ------------------------------------------------------------------------------ def sum (n): """Compute the sum of the first n positive integers, recursively. >>> sum (10) 55 Params: n (int) n >= 1 Returns: (i...
40790b4cb009cd806100c39dbdcd6f5c6a13070b
fhossain75/CS103-UAB
/lab/lab04/min_stubbed.py
474
4.03125
4
# 19fa103; john k johnstone; jkj at uab dot edu; mit license def myMin (L): """Minimum element of a nontrivial list of integers. >>> myMin ([42, -3, 101, 100]) -3 Params: L (int list) a nontrivial list of integers (len(L) > 0) Returns: (int) the smallest element """ return L = [42, -3,...
734a20e81b82f1820e8a70888e16844741b4a58f
fhossain75/CS103-UAB
/lab/lab13/lab13_19fa103.py
6,276
4.09375
4
#!/usr/bin/env python3 # CS103; john k johnstone; jkj at uab dot edu; mit license from random import * ################################################################################ # some statistical tools to analyze the quality of your answers # PLEASE DO NOT CHANGE def mean(X): """Mean. Params: X (l...
3fbe28eaf7e972df0dc5c38e6adcc6857769fccd
fhossain75/CS103-UAB
/lab/lab07/reverse_stubbed.py
441
4.375
4
# 19fa103; john k johnstone; jkj at uab dot edu; mit license # reverse1 iterates over the element; # this is the one to remember, since it is the most natural and clear; # so this is the one to practice def reverse1 (s): """Reverse a string, iteratively using a for loop (by element). >>> reverse1 ('garden') ...
740e6a80e7f19bdfae9f54eb9566b7059481a1a5
kodeskolen/inspiria_h21
/Dag1/live_koding/10print.py
683
3.59375
4
# -*- coding: utf-8 -*- """ Created on Wed Aug 18 09:35:36 2021 @author: Marie """ import turtle from random import randint x = 100 y = 100 steg = 10 turtle.tracer(0) penn = turtle.Turtle() for y in range(-300, 300, steg): for x in range(-300, 300, steg): mynt = randint(0, 1) penn.penup...
bf82e1ce0c691a46090795bf4aaf65190d5782af
rrshaban/misc
/dp.py
1,543
3.625
4
#!/usr/bin/python3 # Program will use (kind of) Dijkstra's algorithm to find the # maximum value-path across the int array s, printing out the # final path and the total path value s = [[0,5,0,8,1,8], [3,6,1,3,6,3], [9,5,7,9,1,1], [8,7,9,4,8,3], [7,8,7,6,2,5], [3,4,0,5,0,4]] def main(s): track = list() t...
d62718594c1c3b23dbbb44568f3ed1a5440c966e
BIGG000/Data-Science-Learning-Track
/Project Code/Machine Learning/Supervised Learning/Linear Regression/script.py
841
3.84375
4
import codecademylib3_seaborn import pandas as pd import matplotlib.pyplot as plt import numpy as np from sklearn import linear_model df = pd.read_csv("https://content.codecademy.com/programs/data-science-path/linear_regression/honeyproduction.csv") print(df.head()) prod_per_year = df.groupby('year').totalprod.mean(...
ed5ef857d879cae9bb386156e3292bbb25554caa
BIGG000/Data-Science-Learning-Track
/Project Code/Python/Project 3 Sal's Shipping/script.py
1,380
3.765625
4
flat_charge = 20.00 price_per_pound = 0 def ground_shipping(weight): if weight <=2: price_per_pound = 1.50 elif weight >2 and weight <=6: price_per_pound = 3.0 elif weight > 6 and weight <=10: price_per_pound = 4.0 else: price_per_pound = 4.75 return weight * price_per_pound + flat_charge # f...
4a26044a0ae157d29fc30ee647dfc693639eb2e5
pythonkila/random
/fun/shoutout.py
682
3.953125
4
# 10 May 2020 # The code takes in an input ( a greeting ) and shout out greeting n number of time. hail = input('Enter your shoutout!...').upper() while hail.isalpha() == False: hail = input('Enter a valid shoutout!...').upper() reps = input('How many Gbosa !...') while reps.i...
88d5d994464caf600976cb520096c743b034e5aa
SauravMahalik/PathaPadha-DS-P-1
/class 5/assignment/p2.py
176
3.859375
4
def unique_list(l): num = [] for a in l: if a not in num: num.append(a) return num print('unique elements are') print(unique_list([1,2,4,5,4,5,6,9,10]))
b3ceb76f891060c68d71f2c1433b20c60968f29d
SauravMahalik/PathaPadha-DS-P-1
/class2/assignment/p6.py
271
4.09375
4
max = 30 et = 0 ot = 0 for n in range(20, max + 1): if(n % 2 == 0): et = et + n else: ot = ot + n print("The Sum of Even Numbers from 20 to {0} = {1}".format(n, et)) print("The Sum of Odd Numbers from 20 to {0} = {1}".format(n, ot))
bfc8c42b230c125a9720829c6dd7126e699d9a69
JessicaNations/STUDIOS
/FLICKLIST/FLICKLIST2/main.py
1,895
3.515625
4
from flask import Flask, request app = Flask(__name__) app.config['DEBUG'] = True page_header = """ <!DOCTYPE html> <html> <head> <title>FlickList</title> </head> <body> <h1>FlickList</h1> """ page_footer = """ </body> </html> """ # TODO: # Name the action for the form '/cross...
82ac58e1b233115eecce7e40189dec930505fceb
AlexanderFabisch/gmr
/examples/plot_sample_gmm_confidence_interval.py
2,110
3.53125
4
""" ======================================== Sample from Confidence Interval of a GMM ======================================== Sometimes we want to avoid sampling regions of low probability. We will see how this can be done in this example. We compare unconstrained sampling with sampling from the 95.45 % and 68.27 % c...
2ed8661a9b9a192286622bd9efb3b5353179862d
bbitmaster/pyrlcade
/pyrlcade/misc/autoconvert.py
533
3.609375
4
#taken from http://stackoverflow.com/questions/7019283/automatically-type-cast-parameters-in-python #This autoconverts values from string to the proper data type #it has been modified to replace 'None' with None def boolify(s): if s == 'True': return True if s == 'False': return False raise ...
e4cdf160615a2f0f428204ef27a905c37d2682e1
mchappychen/LU-Decomposition
/LUdecomp.py
657
3.9375
4
def multiply(a,b): #returns: [] of a x b[] if(a == 0): exit("Error in multiply(): You can't multiply matrix by 0") result = [] for element in b: result.append(round(element * a,1)) return result def add(a,b): #returns [] of a[]+b[] result = [] if(len(a) != len(b)): exit(...
73b923136062a91e0330695679fe6bf6d366501d
VMatrixTeam/open-matrix
/src/judgesystem/src/worker/judgers/programmingJudger/checkers/baseChecker.py
402
3.703125
4
from abc import abstractmethod class Checker(object): """ @param tag is the name of the checkerStage """ def __init__(self, t_tag): self.tag = t_tag @abstractmethod def check(t_submission): """ @detail this is an abstract method """ p...
6ab9c15a8a008bfdf701040fa061eeecaa971426
traveling-desi/Courses
/Coursera/Data-Analysis/Big Data and Web Intelligence/week8/hw6/asia.py
4,593
3.578125
4
import sqlite3 conn = sqlite3.connect("mydatabase.db") # or use :memory: to put it in RAM cursor = conn.cursor() # create a table cursor.execute("DROP TABLE IF EXISTS asia") cursor.execute("""CREATE TABLE asia (asia text, prob real) """) cursor.execute("INSERT INTO asia VALUES (...
5d77f60441d91d31354b7930b69ec72d3e6b76bd
traveling-desi/Courses
/udacity/Machine Learning Nanodegree/technical_interview_practice/solutions_BAK.py
18,666
3.953125
4
################################### Question 1 ### Search for an Anagram of a substring in a super-string def question1(super, sub): ### Take Care of the corner Cases upfront if type(super) != str or type(sub) != str: return False if sub == super: return True if sub == "": return True len_super = len(s...
d347240883041f719822fcbf4fed052a3741829d
ParrishJ/cs-module-project-recursive-sorting
/src/sorting/sorting.py
2,239
4.1875
4
# TO-DO: complete the helper function below to merge 2 sorted arrays #test_arr = [1, 5, 3, 2] #test_arr_b = [5, 6] def merge(arrA, arrB): elements = len(arrA) + len(arrB) merged_arr = [0] * elements count = 0 while arrA or arrB: if len(arrA) != 0 and len(arrB) == 0: merged_arr[coun...
98d7ddf005bc1c236e4ea3ac3c06ecac4089eb9d
tomhudddson/MOVEAssembler
/src/lexer.py
1,391
3.546875
4
from enum import Enum class Lexemes(Enum): # Single character tokens. HASH = 1, COMMA = 2, RIGHT_BRACE = 3, LEFT_BRACE = 4, SEMI_COLON = 5, HYPHEN = 6, DOLLAR = 7, # Literals IDENTIFIER = 8, STRING = 9, NUMBER = 10, # Keywords MOVE = 11 class Lexer: def __...
383ff9f17cd547ada3b4bca7abd13cf12184d2ce
A-FLY/pyton8
/定义类.py
396
3.640625
4
""" 定义类 """ class RenWu: def __init__(self): self.name = None self.age = None self.sex = None def eat(self, times): if times == 12: print("吃饭") def sleep(self): print("开心") def wanyouxi(self): print("wan") ren1 = RenWu() ren1.age = 18 re...
8393ddf1ce183849578b732960aab84cd2f36d86
A-FLY/pyton8
/反恐精英.py
2,229
4.15625
4
""" 演示反恐精英案例 对一个匪徒 分析: 1.定义人类,描述公共属性 life:100 name:姓名要传参 2.定义出英雄与恐怖分子类 3.定义主函数描述枪战过程 main,创建两个对象 4.定义开枪方法,分成两个方法,Hero Is都有 定义的方法要传入被射击的对象 被射击对象的生命值要进行减少 5.主程序中调用开枪操作 6.开枪操作后,要在主程序中显示每个人的状态信息 7.定义Person类的__str__方法,用于显示每个人的状态 8.设置开枪操作为反复操作 再设置停止条件:一方生命值<=0 停止循环使用break -----------------------修复版------...
e82d36d302dd58787a7dae8cafba843817473da5
A-FLY/pyton8
/ex封装.py
760
4.0625
4
""" 封装 """ class Car(): kemu = "猫" def __init__(self, name, age, user): self.__user = user self.__name = name self.__age = age def get_name(self): print(self.__name) def set_name(self, name): if int(input("请输入主人号:")) == self.__user: self.__name = ...
6a149e7ae6a5dbef8317e271a6a2adad8532faba
kpratihast/dcp
/dcp159.py
345
3.625
4
def firstRecur(s): indiv = [] found = 0 for char in list(s): if not found: if char not in indiv: indiv.append(char) found = 0 else: found = 1 return print(char) if not found: return print("Not found")...
ec294fdf56c87a7a4e354806fca2f932b45b6a8e
MohosinPalash/Python-Programming
/12-math-built-in-functions.py
367
3.8125
4
import math x = 25 print('Power =', math.pow(x, 2)) print('Root =', math.sqrt(x)) print('PI =', math.pi) print('Exponential =', math.e) print('Factorial =', math.factorial(x)) print('Remainder =', math.remainder(x, 2)) print('Tau =', math.tau) y = 25.5 print('Ceiling =', math.ceil(y)) print('Floor =', math.floor(y)) ...
e338ade08db6831427e27c3a8d407256b8982353
MohosinPalash/Python-Programming
/2-data-type.py
655
4.0625
4
'''Variables are of three types: Numeric, Sequence, Dictionarty Numeric: integer, complex, float, boolean Sequence: string, list, set, tuple, range ''' # Numeric Data Types i, f, c, b = 5, 2.5, 3+7j, 5 < 6 variable_type = type(i) print(variable_type) variable_type = type(f) print(variable_type) variable_type = type(c)...
e8948329fa39689320fe2d9a695c407d0f41d41b
apple2373/nn_library
/nn_layers/dropout.py
1,570
3.515625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np from layer import Layer class Dropout(Layer): def __init__(self,drop_prob=0.5): self.drop_prob = drop_prob #probability of keeping a unit active. higher = less dropout self.mask_cache=None def forward(self, X, train=True): ...
1e88ed06b72663c12fe7ed00d306e5d4fb533837
Greek-and-Roman-God/Zeus
/baekjoon/question_binarySearch.py
5,461
3.734375
4
# 백준 이분 탐색 # https://www.acmicpc.net/step/29 # 1920번 : 수 찾기 def binary_search_1920(): n = int(input()) A = list(map(int, input().split())) m = int(input()) n_arr = list(map(int, input().split())) # n = 5 # A = [4,1,5,2,3] # m = 5 # n_arr = [1,3,7,9,5] A.sort() if len(A) != n or len(n_arr) ...
e92e19179b0921ab881e74624d30d3b919bda142
Greek-and-Roman-God/Zeus
/jump_to_python/chap4_input_output.py
1,958
3.5625
4
# 점프 투 파이썬 # 4장 연습문제 # 프로그램의 입력과 출력 # Q1 주어진 자연수가 홀수인지 짝수인지 판별해주는 함수 is_odd를 작성해보자 def is_odd(): n = 13 #주어진 자연수 result = "짝수" if n % 2 != 0 : result = "홀수" print(result) # Q2 입력으로 들어오는 모든 수의 평균값을 계산하는 함수 작성 #(입력으로 들어오는 수의 개수는 정해져있지 않음) def avg_all(*args): result = 0 sum = 0 for num in args: ...
f242cf4415956523b55d73ee07c4bb58f44b1550
rydevera3/CourseraDataScienceInPython
/CourseraDataScienceInPythonWeek1.py
1,864
3.953125
4
""" Created on Mon Jun 9 17:42:06 2014 @author: Ryan de Vera Codes for Coursera's Data Science Track in Python """ """ Given a list in Python x=[3,5,1,10,6,2] what code will set the elements less or equal to 6 equal to zero """ """ For this a list comprehension can be used """ x=[3,5,1,10,12,6] y=[0 if i<=6 else i ...
19e49860c0d51c4dfe77dd6fcbfc1afefea33f3a
sqhl/review
/编 程 题/5.去重.py
344
3.859375
4
#集合去重 a=list(set([1,2,3,4,2])) print(a,type(a)) #用字典 这种方法不会保存原有的顺序 l1=['b','c','b','d'] l2={}.fromkeys(l1).keys() print(l2) #使用排序了方式来 l2=list(set(l1)) l2.sort(key=l1.index) print(l2) #列表推导 l1=[1,2,3,2,4,2] l2=[] [l2.append(i) for i in l1 if not i in l2] print(l2)
c18382f6f82bd6d98f293d08ac885a5d78fad773
sqhl/review
/坑向/range的加深理解.py
264
4.15625
4
x = 4 # for i in range(x): # print(i, x) # x = 2 # print(x) # print("------------") for i in range(x): for j in range(x): print(j, x) x = 2 # range(2) 返回一个对象 当每次range完了之后 会重新创建对象
e695338ba9b07b626188652f3123a3e1374808a5
sqhl/review
/17.lambda+python函数式编程.py
515
3.578125
4
#简单,不会浪费空间来保存,它只会计算,不会像声请一个函数一样占用内存空间 #过滤器:filter:调用bool来遍历每个元素,返回一个为true的序列 a = [1,2,3,4,5,6,7] b = filter(lambda x: x > 5, a) print(list(b)) #map是对序列的每个项都执行函数 c = map(lambda x:x*2,[1,2,3]) print(list(c)) #reduce函数是对一个序列的每个迭代调用函数,下面是求3的阶乘 from functools import reduce print(reduce(lambda x,y:x*y,range(1,4))) ...
dcde5b83a659e2c3d79e4244ce296e017963df27
sqhl/review
/9.args和kwargs.py
450
3.734375
4
def a(*args): #args是接受任意数量的参数 for i in args: print(i) a(1,2,3) def b(**kwargs): for i in kwargs.items(): print(i) b(apple = 'fruit', cabbage = 'vegetable') #kwargs接受命名好的参数传入 #*args必须在**kwargs前面 #调用的时候也可以用这种语法 *和** def a(b,c,d): print(b,c,d) e=[1,2,3] a(*e)#当然e中的参数数量必须与a中的传入参...
b8e53d003eef30e4c7916b89770cc4021474cf0f
sqhl/review
/坑向/默认参数.py
540
3.765625
4
def add_end(list=[]): list.append('END') return list print("例1:") print("call add_end(1, 2, 3)") print( add_end([1, 2, 3]) ) print print("例2:") print("call add_end(\"x\", \"y\", \"z\")") print( add_end(["x", "y", "z"]) ) print("上面两个例子不会出问题") print print("试试调用两次add_end不带参数") print...
d8898499e822e8bf5fdfa62e6263fb785ca5836a
Ethic41/programming_challenges
/problems/cops_and_devu.py
561
3.515625
4
# Author: Dahir Muhammad Dahir # Date: 06-June-2019 11:47 PM # About: I will tell you later def main(): test_cases = int(input()) for case in range(test_cases): m, x, y = list(map(int, input().strip().split())) houses = list(map(int, input().strip().split())) max_searchable_house =...
a274e0f071db54e667bf7d089a416e4c18600d96
Ethic41/programming_challenges
/problems/3n+1_problem.py
950
3.921875
4
# Author: Dahir Muhammad Dahir # Date: 23rd-05-2019 # About: 3n + 1 problem max_chain = 0 def main(): # this hold the beginning and ending values as integers start, end = map(int, input().split()) # looping through all integers from 'start' to 'end' for i in range(start, end+1): chain = algo...
ac01424924d3082b97d42609b21f6776569ea8bf
Lucassass/kunstigIntelligenceF21
/lab3/Exercises/aStar.py
4,015
3.890625
4
class Node: # Node has only PARENT_NODE, STATE, DEPTH def __init__(self, state, parent=None, depth=0, distance=0): self.STATE = state self.PARENT_NODE = parent self.DEPTH = depth self.DISTANCE = distance def path(self): # Create a list of nodes from the root to this node. ...