blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
d91f8c6f3078c969d6efec2b9f38583e18ca4057
hbcelebi/leetcode
/#34_First_Last_Position_of_Element/main.py
2,202
3.96875
4
""" Created on Mon May 3 14:40:08 2021 @author: hbc """ # This is a O(N) computational complexity and O(1) space complexity solution to the problem from typing import List ### Here starts my code class Solution(object): def searchRange(self, nums, target): # The algorithm first finds the initial positi...
dcb3a69cba18bcf1049581c10e4b0ebe1b2de839
alanjimenez21/Python-Programming
/Python_Programming/Lab02Part1.py
946
4.03125
4
""" PROBLEM 1 A hotdog stand sells hotdogs, potato chips and sodas. Hotdogs are $2.50 each. Potato chips are $1.50 per bag. Sodas are $1.25 per cans. Design a program to do the following. Ask the user to enter number of hotdogs, chips and sodas ordered by the customer. The program will calculate and display the to...
43ce9547597ddefbeb4adc9ef6ff25eb1a69120d
stevenhuangcode/programming
/Quiz Python.py
1,349
4.0625
4
# Quiz Game correct = 0 incorrect = 0 # Question 1 if input("What is the name of the famous tower in Paris?").lower() == "eiffel": print("Correct") correct += 1 else: print("Incorrect") incorrect += 1 # Question 2 Donnie_Yen = input("How many Ip Man movies are there (ft. Donnie Yen)") if Donnie_Yen =...
5f82bae6c5e2b1ddd90221e14b5b15d8d831a0c9
jessewalton/Practice-Problems
/python/soldier_game/soldier_game_oop.py
1,575
3.515625
4
#!/usr/bin/env python class SoldierGame(object): soldier_health = [] soldier_class = [] soldier_attack = [] """ def add_soldier(self, _health, _class, _attack): soldier_health.append(100) soldier_class.append(0) soldier_attack.append(0) """ def addSoldier(self, soldier_instance): self.soldier_healt...
e65e559b186bd83f1d3611eee3dde6885f87e688
cutieskye/algorithmia
/dynamic-programming/placing_parentheses.py
1,381
3.546875
4
import sys def evaluate(a, b, operation): if operation == '+': return a + b if operation == '-': return a - b if operation == '*': return a * b assert False def extrema(i, j, minima, maxima, operations): minimum = sys.maxsize maximum = -sys.maxsize - 1 ...
7277fe4d8193078e028d761da397fd714c736799
gustavofcosta/curso-python
/Totos exercícios e desafios/ex044.py
977
3.890625
4
print('=='*50) print('Calculadora de desconto ou juros, conforme a forma de pagamento.') print(' '*50) produto = float(input('informe o valor do produto R$ ')) print('Qual é a forma de pagamento?') print(' '*50) print(''' [1] - À vista dinheiro/cheque 10% de desconto. [2] - À vista cartão 5% de descont [3] - Em até...
da4033aecd44cb88fd090aaa6e829d688178bc48
yadavraganu/Codeforce
/1000/Donut_Shops.py
252
3.625
4
for i in range(int(input())): arr=list(map(int,input().split())) a=arr[0] b=arr[1] c=arr[2] if a<c: a1="1" else: a1="-1" if c<a*b: b1=b else: b1='-1' print(str(a1)+" "+str(b1))
fe725b9712f2046af414b8ec25ee638d4c351f54
boconlonton/python-deep-dive
/part-3/4-specialized_dictionary/1-default_dict.py
3,125
3.625
4
"""defaultdict""" from collections import defaultdict, namedtuple from datetime import datetime from functools import partial, wraps counts = defaultdict(lambda: 0) sentence = "able was I ere I saw elba" for c in sentence: counts[c] += 1 print(counts) print(isinstance(counts, defaultdict)) # True print(isinstanc...
aabf61afa9492620a637fea2b46a298dd89ff3da
gustavo-mota/programming_fundamentals
/8_Sétima_lista/1.2_cc/1.2.py
522
3.734375
4
string = str(input("Digite o nome sem espaços no fim: ")) sobre = [] novo_nome = [] for i in string: novo_nome.append(i) x = len(novo_nome) - 1 while x > 0: if ord(novo_nome[x]) == 32: break else: if ord(novo_nome[x]) >= 97 and ord(novo_nome[x]) <= 122: novo_nome[x] = chr(ord(nov...
029459a5c18b52788819a9738844c98cfc69a81b
SurakshaRV/python-lab-1BM17CS108
/rvsFibonacci.py
227
4.03125
4
def fib(n): if n<=1: return n else: return (fib(n-1)+fib(n-2)) n=int(input("how many numbers? ")) if n<=0: print("enter a positive integer: ") else: for i in range(1,n+1): print(fib(i))
e3128c429b227bc4762dcbe9385369a7e447c982
joshtaylora/HackerRank
/CountingValleys/CountValleys.py
1,017
4.125
4
import math import os import random import re import sys # # Complete the 'countingValleys' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. INTEGER steps # 2. STRING path # def countingValleys(steps, path): downDist = 0 upDist = 0 valC...
24ad8ff5db3fd0744f2f7d54f50a29fbc75a5d70
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/Pirouz_N/lesson08/sparsearray.py
17,807
3.640625
4
#!/usr/bin/env python3 """ Purpose: Sparse Array python certificate from UW Author: Pirouz Naghavi Date: 07/13/2020 """ # imports from collections.abc import Sequence import operator class SparseArray: """Sparse Array is data structure for spare data. The list hold information describing the HTML element as...
45934f287630608a4298ac6a5b627e0266dd363d
tomasmarcenaro/Tic-Tac-Toe-project
/tictactoe.py
4,464
3.796875
4
# write your code here movs = "_________" movs2 = [movs[0:3], movs[3:6], movs[6:9]] print("---------") for s in movs2: print("|", *s, "|") print("---------") row_winX = None row_winO = None col_winO = None col_winX = None diag_winX = None diag_winO = None winner = any([row_winX, row_winO, col_winX, col_winO, diag_...
ffd3b9d9d940171b060575665f8f9ade3bd3101c
AkilaSachin/Binary-Tree
/Binary Search Tree/Binary Search Tree.py
3,993
4.0625
4
# Creating the Binary node class class binaryNode: def __init__(self, data): self.data = data self.left = None self.right = None # Adding new child to node def addChild(self, data): if data == self.data: return if data < self.data: if self.le...
ac49270a8fa76c3715502212e597638ef8b8fab3
JulianCSalazar/Python_Tutorial
/Sorting Algorithms.py
4,393
4.125
4
def merge(L, R): print(L) print(R) L_i, R_i = 0, 0 temp = [] while (L_i < len(L)) and (R_i < len(R)): if (L[L_i] < R[R_i]): temp.append(L[L_i]) L_i = L_i + 1 else: temp.append(R[R_i]) R_i = R_i + 1 if L_i == len(L)...
9478534055d40df30b7eca244b1c3d1a6774e7ca
BigBlackWolf/LeetCodeProblems
/DynamicProgramming/maximum-subarray.py
588
4.0625
4
""" Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. Example: Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. Follow up: If you have figured out the O(n) solution, try coding another so...
1f8b0b8f424ff5c82ae3e9b2dd3e407c109ad0dc
KF10/ichw
/pyassign2/currency.py
1,856
4.15625
4
#!/usr/bin/env python3 """currency.py: provide a 'exchange' function which return the amount of another currency when you want to convert a certain amount of currency to another. __author__ = "Kuangwenyu" __pkuid__ = "1800013245" __email__ = "w.y.kuang@pku.edu.cn" """ from urllib.request import urlopen import j...
aafe2cd67a5b4ab6e3c7d8e33abfe770830717bc
kos0ng/code-challenge
/ProblemSolvinghackerrank/sequenceequation.py
576
3.578125
4
#!/bin/python import math import os import random import re import sys # Complete the permutationEquation function below. def permutationEquation(p): ind=[] for i in range(len(p)): ind.append(p.index(i+1)+1) result=[] for i in ind: result.append(p.index(i)+1) for i in result: print i if __name__ == '__main...
6da46c0e975d4ff98e67b71914bb9e57d609220e
Justintime8/Python_Coding
/loops_dictionaries.py
121
3.859375
4
food = {'french fries' : 1, 'ice cream' : 8, 'kbbq' : 19, 'jian bing' : 88} for key in food : print(key, food[key])
4c0a9fcd022e936324a290302bfa3b7c4bd610ba
git-ahi/pomodoro-api
/app/auth/v1/models/user_models.py
863
3.609375
4
class UserModels: """ Class for the user operations """ users = [] def __init__(self, username, task, task_timer, break_timer, task_completed): """ Initialize the user models """ self.id = len(UserModels.users) + 1 self.username = username self.task ...
9abd108e7e72f6a0db7a2fcb2da64fbb97575d61
conor-mcmullan/Scoring-Player-System
/scoring_system.py
3,982
3.78125
4
import thread score_system = {} def set_player_list(player_count): score_system.clear() for player in xrange(player_count): score_system.update({chr(ord('a')+player): 0}) def print_scoreboard(): for key in sorted(score_system): if key is sorted(score_system)[-1]: v = "%s: %s" el...
500f9ee3ff8f16ef1e5904f4d043b9d05f9bc9e6
Donkey-1028/algorithms
/alghorithms-of-everyone/quick_sort.py
1,692
3.671875
4
""" 퀵정렬 Median of Three 방식 """ def choice_pivot(arr, left, right): """ 리스트의 첫번째값, 마지막값, 가운데값중 어떠한 값을 pivot 으로 이용할지 정렬하고 리턴 """ center = (left + right) // 2 if arr[left] > arr[right]: arr[left], arr[right] = arr[right], arr[left] if arr[center] > arr[right]: arr[center], arr...
dab053eeafd8ebdeb1f9314c7b27648175f98bfc
abbisQQ/Server-Client-in-python-simple-and-threaded-for-more-than-one-connection-at-a-time
/server.py
1,312
3.640625
4
import socket import sys # Create a Socket() def create_socket(): try: global host global port global s host = "127.0.0.1" port = 9999 s = socket.socket() except socket.error as msg: print("Socket Creation Error: " + str(msg)) # Binding the socket and ...
6cd97f1b067f7988aa03dc252feebba05b4e4a19
Zhangmingyang-Su/Data-Structure-and-Algorithm
/BFS.py
2,002
3.828125
4
# Vertical Traversal for a Binary Tree #Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column). #If two nodes are in the same row and column, the order should be from left to right. # Input: [3,9,20,null,null,15,7] # 3 # / \ #...
dfb178847d6a18bb405251e33f383b25b7cd2f06
t0kage/palettes
/imagehelper.py
397
3.578125
4
from PIL import Image, ImageDraw def draw_image_from_palette(palette, height): paletteout = Image.new('HSV', (len(palette)*height, height), color=255) palettedraw = ImageDraw.Draw(paletteout) for i in range(len(palette)): shape = (height * i, height, height * (i + 1), 0) ...
32c2dfdba80a9c2fb6889545ef6b07a6e588ea4b
fshahinfar1/SlidingPuzzle
/board.py
3,286
3.578125
4
import pygame import card from random import randrange tmp = [0, 1, 2, 3, 4, 5, 6, 7, 8] white = (255, 255, 255) class Board(object): def __init__(self): self.grid = [] self.z_pos = [2, 2] lst_tmp = [] count = 1 self.cols , self.rows = 3, 3 for i in range(self.cols)...
d003b7b30059067b1138037c409a3b1fcda98244
mohanRajCodes/python-project-todo
/buttonLearn.py
1,077
3.75
4
#####Button##### from tkinter import * import tkinter #import tkMessageBox from tkinter import messagebox top = Tk("Hello","Hello") def sayHello(): #messagebox = "Hello World !!!" #Text = "Hello " #Message = "Hello Message" #tkinter.messagebox.showinfo("Hellow", "World"); messagebox.showinfo("...
17e32ef0c8e37e87d29256cf6fab48593ffcf17e
wxhheian/ptcb
/ch2/ex2_1.py
821
4.09375
4
#你需要将一个字符串分割成多个字段,但分割符号(包括空格)不是固定的 #string对象的split()方法只适用于简单的字符串分割,它不允许有多个分割符 #re.split()分割字符串适用不同的分割符号 #正则表达式分割字符窗 import re def split_str(): line = 'asdf fjdk; afed, fjek,asdf, foo' print(re.split(r'[;\s,]\s*',line)) print(re.split(r'(;|,|\s)\s*',line)) #正则表达式如果使用了()捕获分组,那么被匹配到的文本也将出现在结果列...
c0fb24ecb5f350eebdf4c7df607c30c1a6fb40d4
lozanocelia/DyClee
/datasets/customCircunferencesDataset.py
3,002
3.625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from math import pi, cos, sin, radians import random # config ------------------------------------------------------------------------------------------ # circumference properties h = 0 k = 0 ratio = 1 maxRatioInc = 0.5 ratioPortionForCenterPoints = 10 / 100 * ratio # bat...
a0e39f647eb81dad3737c78f859ccf576dc8fca3
iamdoublewei/Leetcode
/Python3/2363. Merge Similar Items.py
2,712
3.734375
4
''' You are given two 2D integer arrays, items1 and items2, representing two sets of items. Each array items has the following properties: items[i] = [valuei, weighti] where valuei represents the value and weighti represents the weight of the ith item. The value of each item in items is unique. Return a 2D integer arr...
32e85340ccf3c97854074f9f845664c8a5102c3e
OldDon/UdemyPythonCourse
/UdemyPythonCourse/string_formatting.py
989
3.8125
4
name = "Dave" age = 50 accurate_age = 49+11/12 print("Hello %s is %d years old. Or better yet, %f years old." % (name, age, accurate_age)) # %s format string # %d format integer ...
700a02d84ec74c21d8ed06e4c8767625fb31ff6c
Kylar42/wvup
/Project Euler/euler220c.py
1,698
3.734375
4
import time listOfPowers=[] for i in range(0, 50): listOfPowers.append(pow(2,i)) def divisiblePowerOf2odd(someNumber): #print "number looking at is: %i" % someNumber for i in range(0, len(listOfPowers)): pow = listOfPowers[i] if(0 == someNumber % pow): dividend = someNumber / pow if(0 == dividend % 2): ...
fc2e695e9d09d0d62ee8bcaccb975d6f4e64fabe
GlitchLight/Algorithms_DataStructures_Python
/Алгоритмы/Базовые алгоритмы/Небольшое число Фибоначчи/small_fibo.py
442
3.703125
4
# Дано целое число 1 <= n <= 40. Вычислить n-e число Фибоначчи def fib(n): # put your code here if n == 0: return 0 elif n == 1: return 1 else: a = 0 b = 1 for i in range(2, n + 1): F = a + b a = b b = F return F def m...
c3c23f50ca59841ffc24dcd595f692544cd8476f
curiousTauseef/Face-Recognizer
/interface.py
1,442
3.75
4
import tkinter as tk class App(tk.Tk): """ Basic app class to initialize everything """ def __init__(self, title: str = None, size: tuple = None) -> None: super().__init__() self.geometry('{}x{}'.format(size[0], size[1])) self.size = size self.bind('<Escape>', self.kil...
832f5de6e017bf726afcc9813423812316808670
krnets/codewars-practice
/8kyu/Find Maximum and Minimum Values of a List/index.py
1,510
4
4
# 8kyu - Find Maximum and Minimum Values of a List """ Your task is to make two functions, max and min that take a(n) array/vector of integers list as input and outputs, respectively, the largest and lowest number in that array/vector. maximun([4,6,2,1,9,63,-134,566]) returns 566 minimun([-52, 56, 30, 29, -54, 0, -1...
61290954e301f984a07dc1c7d8159ce9602e1914
bozhikovstanislav/Python-Fundamentals
/List-Dictionarys/List_HomeWork/06.OddNumberAtOddPosition.py
244
3.828125
4
from typing import List number_list = list(map(int, input().split(' '))) list_odd: List[int] = [] list_odd = [print(f'Index {x} -> {number_list[x]}') for x in range(0, len(number_list)) if x % 2 != 0 and number_list[x] % 2 != 0]
d55cee6bf20e0cab58ed87dac7135e7d9631f861
mfreund/python-labs
/08_file_io/08_01_words_analysis.py
585
4.34375
4
''' Write a script that reads in the words from the words.txt file and finds and prints: 1. The shortest word (if there is a tie, print all) 2. The longest word (if there is a tie, print all) 3. The total number of words in the file. ''' word_list = [] with open('words.txt', 'r') as words: for word in words.re...
d0d36c703297f42c876a546e7bad230bb1472158
EliakinCosta/python_sessao_da_tarde
/code/numeros_pares_certo.py
91
3.765625
4
lista = [1, 2, 3, 4, 5, 6, 7, 8] print([elemento for elemento in lista if elemento%2==0])
c7239c264302414454693a6ad824499ac0007558
JoshCLWren/python_stuff
/map.py
453
4.09375
4
num = [2, 4, 6, 8, 10] doubles = list(map(lambda x: x*2, num)) print(doubles) people = ["josh", "me", "too"] peeps = map(lambda name: name.upper(), people) list(peeps) print(peeps) # map(function or lambad here: iterator, what you are iteratin) returns the item mapped with the function performed on each element ...
1763dbf110d5348a2697f5f34ea4a86266e47a90
acaciooneto/cursoemvideo
/ex_aulas/ex.aula9-022.py
191
3.609375
4
nome = input('Digite seu nome completo: ') print(nome.upper()) print(nome.lower()) print(nome.title()) name = nome.split() joi = ''.join(name) print(len(joi)) print(name) print(len(name[0]))
b681a6b9a43fc18140c325d0e77e3bb0387097e6
naveen6797/python-tutorials
/programs/odd_or_not.py
188
4.3125
4
number = int(input("enter number:")) if number % 2 != 0: print("{} is odd number".format(number)) else: print("{} is not odd number".format(number)) print("program is completed")
60e703f031930da758af9e094df059e85f554e4c
forzen-fish/python-notes
/10.面向对象下/2单继承与多继承.py
781
3.984375
4
""" 单继承 class Dog(object): def __init__(self,color = "white"): self.color = color def run(self): print("run") class RED_Dog(Dog): pass dog1 = RED_Dog("red") dog1.run() print(dog1.color) 父类的私有方法和私有属性是不会被子类继承的,也不能被子类访问 """ """ 多继承 子类继承多个父类 语法格式: class 子类(父类1,父类2...) 代码 class 陆地生物: d...
36e20861253990eed5deaade35ecb4aa9325d4c0
michaelcyng/python_tutorial
/tutorial6/while_loop_examples/break.py
357
4.25
4
print("Please enter a positive integer") required_count = int(input()) count = 1 print("Start counting") while count <= required_count: # The following runs as long as this condition is true print("Count: {0}".format(count)) count += 1 if count > 5: print("Count is greater than 5. Exit the loop") ...
2bfa29f73a3bd92d34a316489fd0c8d9b16e8e89
karthikgvsk/project-euler
/p34.py
860
4.03125
4
# Digit factorials # upper bound is important from math import log def getDigits(num): l = [] while num > 10: l.append(num % 10) num = num // 10 if num == 10: l.append(1) l.append(0) else: l.append(num) return l # producing the factorial list factList = [1] i = 1 prod = 1 while i <= 9: prod = prod * i...
a05ceb6d95e4271e5342de877f075d24d3e88593
janeosaka/AdventOfCode
/2020/day5/Day5_BinaryBoarding.py
737
3.59375
4
def open_file(): with open('../seats.txt', 'r') as f: seat_list = f.readlines() return seat_list def part1(): seat_list = open_file() seats = [] for record in seat_list: record = (record.replace('F', '0').replace('B', '1').replace('R', '1').replace('L', '0')) row = int(reco...
c53361d698f1e4991cb0a691ccccf367a1b293b3
kashyap1810/pythonbasics-
/list.py
315
3.96875
4
#list employees=['adam','john','greg','danna','ashley'] print('employees length : '+ str(employees.__len__())) employees[1]='jack' print(employees) employees.insert(3,'mavrik') print(employees) employees.remove('mavrik') print(employees) employees.append('mavrik') print(employees) employees.pop() print(employees)
767deef8f9cbf2ae558b5d42aaa2ed0866082cf7
ejonakodra/holbertonschool-machine_learning-1
/pipeline/0x04-data_augmentation/5-hue.py
430
3.765625
4
#!/usr/bin/env python3 """ Defines function that changes the hue of an image """ import tensorflow as tf def change_hue(image, delta): """ Changes the hue of an image parameters: image [3D td.Tensor]: contains the image to change delta [float]: the amount the hue...
5634707575cfaa10215d34abb0d39ab42748c7a8
kolevatov/python_lessons
/week4/4_9.py
963
4.28125
4
# Быстрое возведение в степень """ Возводить в степень можно гораздо быстрее, чем за n умножений! Для этого нужно воспользоваться следующими рекуррентными соотношениями: aⁿ = (a²)ⁿ/² при четном n, aⁿ=a⋅aⁿ⁻¹ при нечетном n. Реализуйте алгоритм быстрого возведения в степень. Если вы все сделаете правильно,то сложнос...
1be6126987ffad639cf9fdadf4073cfabc8b5aae
shubham1172/pyfinbar
/pyfinbar/stock_record.py
1,222
3.625
4
from pyfinbar.console import Colors class StockRecord: '''StockRecord represents the state of a stock. Ticker is the stock symbol. Prevclose is the last day's closing price. Close is today's closing price. usage: record = StockRecord("YESBANK", 12, 14.5) ''' def __init__(self, ticke...
2adcce7c1c754878c998011df308de8d56787f33
Foknetics/AoC_2019
/day_15/part2-1.py
1,520
3.53125
4
import json with open('tile_map.json') as tile_data: string_map = json.load(tile_data) tile_map = {} for coord in string_map.keys(): x, y = coord[1:-1].split(', ') tile_map[(int(x), int(y))] = string_map[coord] def print_map(): output = '' for y in range(21, -20, -1): row = '' for...
1240a0f951459bf4d50a7a78c6c315c9d9ff0472
nathanychin/Python-MySQL
/main.py
1,332
3.53125
4
from database import cursor, db def add_log(text, user): sql = ("INSERT INTO logs(text, user) VALUES (%s, %s)") cursor.execute(sql, (text, user,)) db.commit() log_id = cursor.lastrowid print("Added log {}".format(log_id)) def get_logs(): sql = ("SELECT * FROM logs ORDER BY created DESC") ...
54ac6f0e4b3a024a298d119291dcf1e38e5bf894
maobinchen/data_structure
/c7/insert_sort.py
903
3.53125
4
from DoublyLinkedBase import PositionalList import random def insertion_sort(L): if len(L) > 1: marker = L.first() while marker != L.last(): pivot = L.after(marker) value = pivot.element() if value > marker.element(): marker = pivot el...
955729066bdc244656809bd520dfb8b45f13efce
SimmonsChen/LeetCode
/周赛/5543. 两个相同字符之间的最长子字符串.py
752
3.875
4
""" 给你一个字符串 s,请你返回 两个相同字符之间的最长子字符串的长度 ,计算长度时不含这两个字符。 如果不存在这样的子字符串,返回 -1 。 子字符串 是字符串中的一个连续字符序列 """ class Solution(object): def maxLengthBetweenEqualCharacters(self, s): """ :type s: str :rtype: int """ res = -2 mylist = list(s) for i, item in enumerate(mylis...
17104dc4e9a0b27958a6e57d5b65ecdbd501bb2c
sungwooman91/python_code
/03.Data_Science/csv_test.py
1,240
3.6875
4
import csv with open("Demographic_Statistics_By_Zip_Code.csv", newline="") as infile: data = list(csv.reader(infile)) ## No1_COUNT PARTICIPANTS countParticipantsIndex = data[0].index("COUNT PARTICIPANTS") print("The index of 'COUNT PARTICIPANTS': %s" % countParticipantsIndex) # print("The index of 'COUNT PARTICIP...
eb076b873094942de4200320d1c3f1e64c7bccdc
pacerrabbit/mock-signup-page
/models.py
1,003
3.578125
4
# Standard libs from collections import OrderedDict # Mock user collection # Maps username to User object. Only stores data in memory, so it won't persist # anything when the app exits. I'm using an OrderedDict so that users will be # listed in the order in which they're created. USER_COLLECTION = OrderedDict() class...
c49d9801cd29c28921e00116463ce6732b58105f
cooleel/HackerRank
/Mini_Max_Sum.py
380
3.828125
4
#!/bin/python3 #by Shanshan Wang #https://www.hackerrank.com/cooleel #!/bin/python3 import math import os import random import re import sys # Complete the miniMaxSum function below. def miniMaxSum(arr): min_ = sum(arr)-max(arr) max_ = sum(arr)-min(arr) print(min_, max_) if __name__ == '__main__': ...
b48e773d9cd3894c3dc7b772d9014ebfc92cf187
joseangel-sc/CodeFights
/Arcade/SortingOutpost/maximumSum.py
1,108
3.671875
4
def maximumSum(A, Q): A.sort() b = [0]*len(A) for q in Q: for i in range(q[0],q[1]+1): b[i] += 1 b.sort() sol = 0 for i in range(len(A)): sol += A[i]*b[i] return sol '''You are given an array of integers A. Range sum query is defined by a pair of non-negative int...
3c7b41a6fccbf14805c150cab1e44d9043f0518f
kalyons11/kevin
/kevin/leet/score_of_parentheses.py
1,671
3.765625
4
""" https://leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/587/week-4-february-22nd-february-28th/3651/ """ class Solution: def score_of_parentheses(self, S: str) -> int: # recursive approach potentially? # need to get down to base cases of (), (A), (AB) # know S is ...
e15bdc4a6356b0ef710261bf94ab3120245d7b3c
LezamaCybart/scientific_computing_with_python_fcc
/probability_calculator/prob_calculator.py
1,280
3.703125
4
import copy import random # Consider using the modules imported above. class Hat: hat = dict() contents = list() def __init__(self, **balls): self.hat = balls for color in self.hat: for number in range(self.hat[color]): self.contents.append(color) def ...
9e699bbab2e386ac0fd8b8bcb3723dc3661a05ab
dogac00/Python-General
/linked-list-python.py
571
3.9375
4
class Node: def __init__(self, value): self.value = value self.next = None def printNode(self): print(self.value, end=" -> None") class LinkedList: def __init__(self, value): self.value = value self.next = None def insertValue(self, value): while self.next: self = self.next ...
6a74266d357961d84c5bfa28c894d348d6bbe95d
SerhiiDior/soft_100_task
/100_tasks/unit_test/problems/2.py
96
3.921875
4
number=int(input("Number=")) fact=1 i=1 while (i<=number): fact=fact*i i+=1 print(fact)
e60e90488ec575599e4bef54832824c5629b8cd0
rajarajann/Labs
/openbook3_task1.py
971
3.65625
4
fin = open ("Bus_Stops.csv") def total_terminals(): fin = open("Bus_Stops.csv") counter = 0 for lines in fin: line_list = lines.split(",") if line_list[10] == "Terminal": counter +=1 print ("Total number of Terminals :", counter) def total_busstop(): fin = open("Bus_S...
fdfb999efb42ecd020cb699359e30e7632a2de0e
Gijsbertk/afvinkblok1
/5.21.py
672
3.84375
4
import random #importeert library print('Je doet steen papier schaar, voor steen kies je 1 voor papier 2 en schaar 3') #print wat je moet doen def main(): game() #roept functie aan def game(): #functie speler = int(input('Kies een nummer voor steen papier schaar: ')) #vraagt om functie comp = random.ra...
be4cc927cf5fcdb7da54ecacf3a5b6a24bd646f5
jamesro/BlackJackLearn
/blackjack/player.py
4,699
3.625
4
#!/usr/bin/python # -*- coding: utf-8 -*- from .cards import * from .hand import Hand from .table import Table class Player: def __init__(self, bank=1000): self.gameState = "" self.table = Table() self.bank = bank self.wins = 0 self.losses = 0 self.pushes = 0 ...
7541be8d53fe79ac6ce7ff459d67f0c3a1804e51
adarshnamsani/exam
/python-test1.py
3,371
4.21875
4
from placeholders import * def get_odds_list(count): """ This method returns a list of the first 'count' odd numbers in descending order. e.g count = 3 should return [5,3,1] """ return None def get_odd_mountain(count): """ odd mountain is a list of odd numbers going up from 1 and then b...
d105ed0b71fc01c837aa6a8fa155b79f7dc66fc1
sridhar667/hello-world
/oddoreven.py
174
3.625
4
n = input() lst = [int(i) for i in n] for i in lst: if i%2==0: lst.remove(i) s = sum(lst) if s%2==0: print('Even') else: print('Odd')
9686d36a56d4e23d947011244a324ae568c81159
larsQue11/knn_electron_app
/backend/knn_iris.py
6,915
3.65625
4
# Course: CS7267 # Student name: William Stone # Student ID: 000-272-306 # Assignment #: 1 # Due Date: September 16, 2019 # Signature: # Score: import numpy as np from math import sqrt import csv import sys #retrieve data from CSV file def getData(dataPath): with open(dataPath) as dataFile: data = np.arr...
5a359f517804a9e8f474a91363bd3684c11c98ec
coding-with-fun/Python-Lectures
/Lec 1/Task/stringOperations.py
814
4.375
4
s = "This is string example" ''' Reverse string ''' reverse = s[::-1] print("Reverse string is: "+reverse) print() ''' Reverse words ''' words = s.split(" ") revWords = [revWord[::-1] for revWord in words] revStr = " ".join(revWords) print("Reversed words are: "+revStr) print() ''' Split and join ''' splitString = s...
00a85601f190c68c0aaad68309463506c2a42221
celsopa/CeV-Python
/mundo01/ex020.py
451
4.09375
4
# Exercício Python 020: O mesmo professor do desafio 019 quer sortear a ordem de apresentação de trabalhos dos alunos. Faça um programa que leia o nome dos quatro alunos e mostre a ordem sorteada. from random import shuffle lista = list([input("Aluno 1: "), input("Aluno 2: "), input("Aluno 3: "), input("Aluno 4: ")]) ...
216290b62d6ae4a1499f9ff309dbfd8cd530a5d4
CSC510-G35-Fall2022/csc510-g35-hw2
/codes/num.py
1,995
3.84375
4
import random as r import math from codes.utilities import utilities as u import codes.commandLine as c class Num: '''Holds number cols and applies functions to them''' def __init__(self, c, s): self.n = 0 self.name = s self._has = [] self.at = c or 0 self.lo = math.inf ...
1f9d49f012f8280ee930b6ed6fb86448da98892e
pangyouzhen/data-structure
/tree/104 maxDepth.py
1,144
3.6875
4
# Definition for a binary tree node. # 插入,删除,查找 from base.tree.tree_node import TreeNode class Solution: def maxDepth(self, root: TreeNode): """ :rtype:最高深度 """ if root is None: return 0 left_depth = self.maxDepth(root.left) right_depth = se...
64a77e1838f97a847cf19e4316ea13ee147e5cd9
mbazhlekova/mit-intro-programming-python
/week 1/lectures/guess-and-check.py
117
3.859375
4
cube = 27 for guess in range(cube + 1): if guess**3 == cube: print("Cube root of ", cube, " is ", guess)
bf4aac580efc2e69b8cd3feefc4fb85d0d177f3e
DiyanKalaydzhiev23/fundamentals---python
/dictionaries - exresice/softuni exam results.py
999
3.71875
4
languages = {} banned = [] results = {} data = input().split("-") while "exam finished" not in data: if "banned" in data: banned.append(data[0]) data = input().split("-") continue name = data[0] language = data[1] points = int(data[2]) current_points = 0 if language i...
8b3fef93387829c36b3081fa1343b5d02613763c
AdamZhouSE/pythonHomework
/Code/CodeRecords/2710/60776/311893.py
517
3.515625
4
list=[] a=input().split(' ') renshu=int(a[0]) yujushu=int(a[1]) for i in range(0,yujushu): a=input().split(' ') if a[0]=='M': list1=[] list1.append(int(a[1])) list1.append(int(a[2])) list.append(list1) else: list1=[] for j in range(0,len(list)): if...
6c0a79810d142cd1e1057cf45a808321e5c5e62e
bf108/Prediction-of-US-City-Temp-with-Linear-Regression
/Predicting_US_Cities_Annual_Temp_Linear_Regression.py
9,475
3.609375
4
import numpy as np import pylab import matplotlib.pyplot as plt import re # cities in our weather data CITIES = [ 'BOSTON', 'SEATTLE', 'SAN DIEGO', 'PHILADELPHIA', 'PHOENIX', 'LAS VEGAS', 'CHARLOTTE', 'DALLAS', 'BALTIMORE', 'SAN JUAN', 'LOS ANGELES', 'MIAMI', 'NEW OR...
f682a67759afb0a5e5b25a77f16bd86bc94c29c7
godxvincent/pythonbasico
/ModuloAccesoBD/BaseDatosRestaurante.py
4,625
3.84375
4
import sqlite3 import os def crear_db(): conexion = sqlite3.connect("restaurante.db") cursor = conexion.cursor() try: sentencia = """CREATE TABLE categoria( id INTEGER PRIMARY KEY AUTOINCREMENT, nombre VARCHAR(100) UNIQUE NOT NULL) """ cursor.execute(sentencia) ...
f619f9942ad4af68e1a9ef369d0f4b036f41cc1a
frclasso/CodeGurus_Python_mod1-turma1_2019
/Cap18_Tkinter/07_label.py
520
3.671875
4
from tkinter import * root = Tk() root.title("Lables") label = Label(root, text="Hey, How are you doing?", relief=RAISED) label.pack() Label(root, text='Sufficient width', fg='white', bg='purple', relief=RAISED).pack() Label(root, text='Width of x', fg='white', bg='green', relief=RAISED).pack(fill='x') Label(root,...
f949ee0f65234c925a8d22b4df252bb5cfd8c137
Fiinall/UdemyPythonCourse
/Loops/Determining Factorial - Alternative.py
438
4.25
4
print(""" Hello I Can Help You to Determine Your Numbers Factorial To Exit Press the "q" """) while True: Number = (input("Please Enter Your Number")) if (Number == "q"): print("Exiting...") break else: Factorial = 1 Number = int(Number)...
9bba419a842ef4d5c1b3a1811bd2a9afb1f7b318
jonasht/cursoIntesivoDePython
/exercisesDosCapitulos/07-entradaDeUsuario-E-lacosWhile/7.3-multiplosDDez.py
170
3.921875
4
n = int(input('\ninforme o numero para ver é multiplo de 10,\nn:')) print('o numero é multiplo de dez' if n % 10 == 0 else 'o numero não é multiplo de dez')
3b37021ba5655f6a5b20e5ceb54294d3cf472bc0
andysai/python
/黑马程序员-python/python从0开始学编程/day03/16-猜拳游戏功能实现.py
565
4.28125
4
""" 1 出拳 玩家:手动输入 电脑:1 固定:剪刀 2. 随机 2 判断输赢 2.1 玩家获胜 2.2 平局 2.3 电脑获胜 """ # 1 出拳 # 玩家 player = int(input("请出拳(0--石头;1--剪刀;2--布):")) # 电脑 computer = 1 # 2 判断输赢 # 玩家获胜 if ((player == 0) and (computer == 1)) or ((player == 1) and (computer == 2)) or ((player == 2) and (computer == 0)) : print('玩家获胜'...
61cd48dd6701147f1438ebba6eb01ee06f766ef7
xtorrentgorjon/Python-Examples
/Multiprocessing/Threads/threads.py
466
3.90625
4
##### # Python Examples: # threads.py # # Simple threading example. # # Xavier Torrent Gorjon ##### import threading THREAD_NUMBER = 4 class thread_class(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.__n = 0 def run(self): n = self.__n while n < 1000: n+=1 print sel...
ead747179025becc977d7e79bd4624438a331426
ajpri/UHD_CS3321-Spr2020-25973-LMS
/functions.py
617
3.875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 4 11:51:57 2020 @author: austin """ grades = ("A", "C", "F") def calcgpa(inputgrades): sum = 0 for grade in grades: if grade.upper() == "A": sum += 4 elif grade.upper() == "B": ...
2581f0e8a881aa7112ca2e1cf5396d673a2962c4
jspencersharp/Portfolio
/Functions/sept7.lecture.py
642
3.6875
4
# class that rep's superhero - name, city, powers, class Hero(): def __init__ (self, name, city, powers): self.name = name self.city = city self.powers = powers hero1 = Hero("superman", "New York", "x-ray vision") print hero1.name #create villain class Villian(): def __init__(sel...
ebdb6a3030065b25ba68888d1943e760a7f88253
machineMachineLearning/PythonProgramming
/program21_RNN.py
23,300
4.03125
4
# we use: http://www.deeplearningitalia.com/wp-content/uploads/2017/12/Dropbox_Chollet.pdf # we use: F. Chollet, Deep learning with Python # RNN # an RNN is a for loop that re-uses quantities computed during the previous iteration of the loop # RNNs, LSTM-RNNs and GRU-RNNs # LSTM-RNNs and GRU-RNNs are better than RNN...
34bb662ffa26ffed3a8e3d795b02c659a9993fb6
liwenkaitop/test
/sort.py
369
3.90625
4
# 冒泡排序 def bubblesort(srcDatas): """对一个列表中的数据进行从小到大的冒泡排序,返回排序成功""" if len(srcDatas)<=2: return True for i in range(0,len(srcDatas)-1): for j in range(0,len(srcDatas)-1-i): if srcDatas[j] > srcDatas[j+1]: data = srcDatas[j] srcDatas[j] = srcDatas[j+1] srcDatas[j+1] = data return True
5f8b8eac76af2502611fe1a213ebeb4ebc5143b0
VaishnaviReddyGuddeti/Python_programs
/Python_Lists/list()Constructor.py
214
4.21875
4
# It is also possible to use the list() constructor to make a new list. #Using the list() constructor to make a List: thislist = list(("apple", "banana", "cherry")) # note the double round-brackets print(thislist)
c23e399f934381d0d7364c423d9b554c1f4e9572
arishabh/HTML-and-CSS
/HTML - INFO-I 101/py4.py
595
4.125
4
import random name = input("Enter your name: ") sentence = "*proper fell on the *adj *noun today." sentence = sentence.split() nouns = ['table', 'chair', 'floor', 'ground', 'staircase', 'playground'] adj = ['huge', 'small', 'tiny', 'enormous', 'humungous'] count = 0; for word in sentence: if (word == '*no...
42b084d6a687ef7acf2d59c8a50bb47d902beca6
jihoondio/leetcode
/1588. Sum of All Odd Length Subarrays.py
528
3.5625
4
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: _sum = sum(arr) arr_sum = [arr[0]] for i in range(1, len(arr)): arr_sum.append(arr[i] + arr_sum[i - 1]) curr_odd = 3 while curr_odd <= len(arr): for j in range(curr_odd - 1, len(a...
575a0095523dd275b7e6a5f89266f4feae0afdbb
UCD-pbio-rclub/Pithon_JohnD
/July_18_2018/Problem_1.py
803
4.125
4
# Problem 1 # Write a function that reports the number of sequences in a fasta file import string import re import glob def fastaCount(): files = glob.glob('*') filename = input('Enter the name of the fasta file if unsure, enter ls for \ current directory listings: ') if filename == 'ls': for i in...
9211ee4ebe955333df1e0e5150510cb8b5f5c6b6
RajashriST/python_demo
/factorial.py
172
3.890625
4
#factorial fact=1 def factorial(x): if x>1: return x*factorial(x-1) elif x==1: return 1 fact=factorial(6) print(fact) #import math #print(math.factorial(5))
d6b13141fee2ead8606aaa9c5f64ce6b0812627c
yiming1012/MyLeetCode
/LeetCode/树(Binary Tree)/834. 树中距离之和.py
1,878
3.65625
4
""" 给定一个无向、连通的树。树中有 N 个标记为 0...N-1 的节点以及 N-1 条边 。 第 i 条边连接节点 edges[i][0] 和 edges[i][1] 。 返回一个表示节点 i 与其他所有节点距离之和的列表 ans。 示例 1: 输入: N = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]] 输出: [8,12,6,10,10,10] 解释: 如下为给定的树的示意图: 0 / \ 1 2 /|\ 3 4 5 我们可以计算出 dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5) 也就是...
760d25432c1695c002f764837262c94f4bcbcf85
linbojun/ResNet
/resnet/Util.py
4,046
3.859375
4
import tensorflow as tf import numpy as np from matplotlib import pyplot as plt import os import random import math def accuracy(logits, labels): """ Calculates the model's prediction accuracy by comparing logits to correct labels – no need to modify this. :param logits: a matrix of size (num_input...
12de4c87d49bb6979b9164a56fb369969f35d763
MiekoHayasaka/Python_Training
/day0202/code4_5.py
324
3.90625
4
count=0 student_num=int(input('学生の数を入力>>')) score_list=list() while count < student_num: count += 1 score=int(input('{}人目の試験の得点を入力>>'.format(count))) score_list.append(score) print(score_list) total=sum(score_list) print('平均点は{}点です'.format(total / student_num))
3f12f4f0fa954c93e271a86042756bc392682866
MAPLE-Robot-Subgoaling/IPT
/data/HW3/hw3_297.py
826
4.0625
4
def main(): temperature = float(input("What is the temperature: ")) print("Please enter C for Celsius or K for Kelvin") choice = input("Celsius or Kelvin: ") if(choice == "K"): tempc = (temperature - 273.15) if (tempc < 0): print("Water is solid at this temperature.") ...
fea35d9e1b68cfed9b91e7cd123ef773870a7967
randolphwong/libdw
/libdw/boundarySM.py
4,128
3.8125
4
""" Very simple behavior for following the boundary of an obstacle in the world, with the robot's 'right hand' on the wall. """ import sm from soar.io import io ###################################################################### # Global Variables #################################################################...
b197426a48c7e62b524bca20bab44726dd521a66
pandeyab/create_your_own_image_classifier
/Part 2 - Neural Networks in PyTorch.py
8,036
3.921875
4
#!/usr/bin/env python # coding: utf-8 # # Neural networks with PyTorch # # Next I'll show you how to build a neural network with PyTorch. # In[1]: # Import things like usual get_ipython().run_line_magic('matplotlib', 'inline') get_ipython().run_line_magic('config', "InlineBackend.figure_format = 'retina'") impor...
5b8b60e383c8ad3b9597a0774b7c55706fcc0497
acbahr/Python-Practice-Projects
/magic_8_ball_gui.py
1,524
4.3125
4
# 1. Simulate a magic 8-ball. # 2. Allow the user to enter their question. # 3. Display an in progress message(i.e. "thinking"). # 4. Create 20 responses, and show a random response. # 5. Allow the user to ask another question or quit. # Bonus: # - Add a gui. # - It must have box for users to enter the question. # - It...
ff245a18811f529e5d756c478819b3f41e2b97ae
elsaVelazquez/faster-pet-adoption
/src/pipelines/data_ingestion/read_in_data.py
511
3.578125
4
import numpy as np import pandas as pd def read_df_csv(path): '''read in file ''' # print('read df') return pd.read_csv(path) #, parse_dates=True, squeeze=True) def read_text_file(fname): '''Reads the filename - should have a .txt extension. Returns a text string containing the entire de...
295e926b58dd752b3d5a392892578746ba8cb2f1
shaheerkhan199/python_assignment
/Assignment1/Q5.py
159
4.25
4
first_name = input("Enter First name:") last_name = input("Enter Last name:") print("your name in reverse Order", first_name.reverse()," ",last_name.reverse())
609c085bed92d83d98b5a63bce2e6e46b90d6665
pedrottoni/Studies-Python
/Cursoemvideo/Mundo2/exercise070.py
1,609
4.09375
4
""" Crie um programa que leia o nome e o preço de vários produtos. O programa deverá perguntar se o usuário vai continuar ou não. No final, mostre: A) qual é o total gasto na compra. B) quantos produtos custam mais de R$1000. C) qual é o nome do produto mais barato. """ amount = greater_thousand = cheapeast_product =...