blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
e84ea0ce2afb28b4bb2c13a0f8b44fbbb08788bc | aayanqazi/python-preparation | /A List in a Dictionary.py | 633 | 4.25 | 4 | from collections import OrderedDict
#List Of Dictionary
pizza = {
'crust':'thick',
'toppings': ['mashrooms', 'extra cheese']
}
print("You ordered a " + pizza['crust'] + "-crust pizza " +
"with the following toppings:")
for toppings in pizza['toppings']:
print ("\t"+toppings)
#Examples 2
favourite... |
2a5a3c3379ac23b7f50123e6e537dea5119119b0 | routedo/cisco-template-example | /configgen.py | 863 | 3.578125 | 4 | """
Generates a configuration file using jinja2 templates
"""
from jinja2 import Environment, FileSystemLoader
import yaml
def template_loader(yml_file, template_file, conf_file):
"""
This function generates a configuration file using jinja2 templates.
yml_file = Location of the file containing variables... |
5a8e4bc36057b004f79a5172b0d7de1754fb3fa5 | BaburinAnton/GeekBrains-Python-homeworks | /Lesson 6/hw 3.py | 831 | 3.59375 | 4 | class Worker:
name = None
surname = None
position = None
profit = None
bonus = None
def __init__(self, name, surname, position, profit, bonus):
self.name = name
self.surname = surname
self.position = position
self.profit = profit
self.bonus = ... |
194f4c01744ab1d09ed9ca3329624b6768e83b60 | BaburinAnton/GeekBrains-Python-homeworks | /Lesson 4/hw 4.py | 129 | 3.515625 | 4 | numbers = [14, 42, 1, 7, 13, 99, 16, 1, 70, 55, 14, 13, 1, 7]
list = [el for el in numbers if numbers.count(el)==1]
print(list) |
a322c9f894dc53a7e56f5f9bca0ee15d4e666209 | Glitchier/Python-Programs-Beginner | /Day 5/sum_of_even.py | 185 | 3.96875 | 4 | sum=0
for i in range(2,101,2):
sum+=i
print(f"Sum of even numbers: {sum}")
sum=0
for i in range(1,101):
if(i%2==0):
sum+=i
print(f"Sum of even numbers: {sum}") |
05a1e4c378524ef50215bd2bd4065b9ab696b80d | Glitchier/Python-Programs-Beginner | /Day 2/tip_cal.py | 397 | 4.15625 | 4 | print("Welcome to tip calculator!")
total=float(input("Enter the total bill amount : $"))
per=int(input("How much percentage of bill you want to give ? (5%, 10%, 12%, 15%) : "))
people=int(input("How many people to split the bill : "))
bill_tip=total*(per/100)
split_amount=float((bill_tip+total)/people)
final... |
f54e2970cd64a45890d02ba9b969257a46642e6f | Glitchier/Python-Programs-Beginner | /Day 9/auction.py | 799 | 3.765625 | 4 | from art import logo
from replit import clear
print(logo)
bid_dic={}
run_again=True
def high_bid(bid_dic_record):
high_amount=0
winner=""
for bidder in bid_dic_record:
bid_amount=bid_dic_record[bidder]
if(bid_amount>high_amount):
high_amount=bid_amount
... |
e88c319709f2822abaea0703fdb94685f3c0de91 | litewhat/internal-linking | /Multiprocessing/m_threading.py | 885 | 3.578125 | 4 | import time
import threading
import multiprocessing
def calc_square(numbers):
print("Calculating square numbers")
for n in numbers:
time.sleep(0.2)
print(f"Square: {n*n}")
def calc_cube(numbers):
print("Calculating cube numbers")
for n in numbers:
time.sleep(0.2)
prin... |
e6cad988204f288958eeb15f365d991b490f6a51 | SharonT2/Practica1IPC2 | /lista.py | 1,696 | 3.875 | 4 | from nodo import Nodo
class Lista():
def __init__(self):#métoedo constructor
#dos referencias
self.primero = None #un nodo primero que inserte el usuario
self.ultimo = None #un nodo que apunta al ultimo nodo
#Creando el primer nodo self, id, nombre, m, n, primero, fin
def inserta... |
ad19b0f9e3453d3148f84f0545159d96b90055a1 | HarkTu/Coding-Education | /SoftUni.bg/Python Oop/03-ENCAPSULATION-exercise/01. Wild Cat Zoo.py | 6,196 | 3.546875 | 4 | class Lion:
def __init__(self, name, gender, age):
self.age = age
self.gender = gender
self.name = name
def get_needs(self):
return 50
def __repr__(self):
return f"Name: {self.name}, Age: {self.age}, Gender: {self.gender}"
class Tiger:
def __init__(sel... |
32a6b5e833eb5d3a78e8f4b03444da335fe910cb | HarkTu/Coding-Education | /SoftUni.bg/Python Advanced/December 2020/GameOfWords.py | 1,068 | 3.59375 | 4 | initial = input()
size = int(input())
matrix = []
p_row = 0
p_column = 0
for row in range(size):
temp = input()
add_row = []
for column in range(len(temp)):
if temp[column] == 'P':
p_row = row
p_column = column
add_row.append('-')
continue
add_... |
c2853ed178330ec79e5ed687780430139a103c48 | HarkTu/Coding-Education | /SoftUni.bg/Python Advanced/August 2020/TaxiExpress.py | 504 | 3.75 | 4 | customers = [int(x) for x in input().split(', ')]
taxis = [int(x) for x in input().split(', ')]
time = sum(customers)
while customers and taxis:
customer = customers[0]
taxi = taxis.pop()
if taxi >= customer:
customers.remove(customers[0])
if customers:
print(
f"Not all customers were d... |
14a7f65f931c18bf4e7fa39e421d1a688e47356c | rg3915/Python-Learning | /your_age2.py | 757 | 4.3125 | 4 | from datetime import datetime
def age(birthday):
'''
Retorna a idade em anos
'''
today = datetime.today()
if not birthday:
return None
age = today.year - birthday.year
# Valida a data de nascimento
if birthday.year > today.year:
print('Data inválida!')
return... |
3ef31c99b25fbb7b23b367ef87e312753a13a3ab | Jiang-Xiaocha/Lcode | /searchMatrix.py | 1,226 | 3.8125 | 4 | '''
Description:
38. 搜索二维矩阵 II
写出一个高效的算法来搜索m×n矩阵中的值,返回这个值出现的次数。
这个矩阵具有以下特性:
每行中的整数从左到右是排序的。
每一列的整数从上到下是排序的。
在每一行或每一列中没有重复的整数。
样例
考虑下列矩阵:
[
[1, 3, 5, 7],
[2, 4, 7, 8],
[3, 5, 9, 10]
]
给出target = 3,返回 2
挑战
要求O(m+n) 时间复杂度和O(1) 额外空间
'''
class Solution:
"""
@param matrix: A list of lists ... |
a858c6ebc8e7f19176cdd4a2c880ff14e7f14011 | challengeryang/webservicefib | /client_sim/httpclientthread.py | 1,955 | 3.5 | 4 | #!/usr/bin/python
#
# author: Bo Yang
#
"""
thread to send requests to server
it picks up request from job queue, and then picks
up one available connection to send this request
"""
import threading
import Queue
class HttpClientThread(threading.Thread):
"""
Thread to send request to server. it's just a wo... |
0b6c0ac5676c1071e9728bb00e8bd258ee40339d | yevheniir/python_course_2020 | /.history/1/test_20200606182729.py | 266 | 3.96875 | 4 | people = []
while True:
name = input()
if name == "stop":
break
if name == "show all":
print(people)
pe
print("STOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOP")
# for name in people:
# if name != "JoJo":
# print(name) |
8ca513cdf45e5f286a6fb29abbebdf69e1e84b44 | yevheniir/python_course_2020 | /l5/untitled-master/HW01_star_novela.py | 2,464 | 3.890625 | 4 | import random
print("Вітаю, Ви Колобок і Вас поставили на вікні простигати. Ваші дії:")
print("1 - втекти")
print("2 - залишитися")
a = input("Виберіть дію: ")
if a == "1":
print("Ви зустріли зайця. Ваші дії:")
print("1 - заспівати пісню і втекти")
print("2 - прикинутися пітоном")
print("3 - прикинут... |
6c12b0a15ff48d7b1707f162d2f7c7c30a28ea02 | yevheniir/python_course_2020 | /.history/1/dz/1st_game_20200613180427.py | 1,110 | 3.75 | 4 | import time
import random
while True:
print("Вітаю у грі камінь, ножиці, бумага!")
time.sleep(2)
відповідь_до_початку_гри=input("Хочете зіграти?(Відповідати Так або Ні)")
if відповідь_до_початку_гри=="Так":
print("Чудово")
else:
print("Шкода")
time.sleep(999999999... |
32bc00c8b8700da494e559fcd8e2558a43b93e03 | suminov/lesson2 | /lessonfor.py | 564 | 3.96875 | 4 | for x in range(10):
print(x+1)
print(
)
word = input('Введите любое слово: ')
for letter in word:
print(letter)
print(
)
rating = [{'shool_class': '4a', 'scores': [2, 3, 3, 5, 4]},
{'shool_class': '4b', 'scores': [2, 4, 5, 5, 4]},
{'shool_class': '4v', 'scores': [2, 2, 3, 5, 3]}]
a = 0
for result in rati... |
edc0c851a098ede4bb3e4e026e4d0bb6f35451d9 | MDaalder/MIT6.00.1x_Intro_CompSci | /W06_AlgoComplexity_BigO/Sort variants bubble, selection, merge.py | 3,349 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 15 16:21:21 2019
@author: md131
Comparison of sorting methods and their complexities in Big Oh notation.
"""
""" Bubble sort compares consecutive pairs of elements. Overall complexity is O(n^2) where n is len(L)
Swaps elements in the pair such that smaller is first.
Wh... |
00a3af0ce1ebf2608eddbc9264cedf965c1d27b7 | MDaalder/MIT6.00.1x_Intro_CompSci | /W07_Plotting/primes_list.py | 881 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 24 16:48:04 2019
@author: Matt
"""
""" returns a list of prime numbers between 2 and N
inclusive, sorter in increasing order"""
def primes_list(N):
'''
N: an integer
'''
primes = []
rangeNums = []
if N == 2:
primes.append(N)
... |
77f89966c4fdf45f1d47c2165f85644ceb9f20fa | MDaalder/MIT6.00.1x_Intro_CompSci | /W02_Simple_Programs/Converting int to binary.py | 888 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 5 20:59:49 2019
@author: Matt
"""
# this program converts an integer number into a binary
# if binary 101 = 1*2**2 + 0*2**1 + 1*2**0 = 5
# then, if we take the remainder relative to 2 (x%2) of this number
# that gives us the last binary bit
# if we then divide 5 by 2 ... |
5e0d0132cee8a9b3aa8f9a417eb8638d3f73ec82 | MDaalder/MIT6.00.1x_Intro_CompSci | /W02_Simple_Programs/polysum.py | 468 | 3.75 | 4 |
"""
@author: Matt
Function calculates the sum of the area and perimeter^2 of a regular polygon to 4 decimal points
A regular polygon has n sides, each with length s
n number of sides
s length of each side
"""
def polysum(n, s):
import math
area = (0.25*n*s**2)/(math.tan(math.pi/n)) # area of... |
e3b9c70022e232ae228e23a4ff155ae4da19cf69 | MDaalder/MIT6.00.1x_Intro_CompSci | /W04_GoodPractices/8 video example of raise.py | 678 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 2 20:37:50 2019
@author: Matt
"""
def get_ratios(L1, L2):
""" assumes L1 and L2 are lists of equal length of numbers
returns a list containing L1[i]/L2[i]"""
ratios = []
for index in range(len(L1)):
try:
ratios.append(L1[index]/float(... |
423a48d5272b44e2156d1f0966c70757007233aa | MDaalder/MIT6.00.1x_Intro_CompSci | /Midterm Problem 5.py | 1,991 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 24 16:38:25 2019
@author: Matt
"""
def uniqueValues(aDict):
'''
aDict: a dictionary
This function takes in a a dictionary, and returns a list
Keys in aDict map to integer values that are unique (values appear only once in aDict)
List of... |
81a509d34b1289560e111cfaf2103fe29f327009 | AlymbaevaBegimai/TEST | /2.py | 401 | 4 | 4 |
class Phone:
username = "Kate"
__how_many_times_turned_on = 0
def call(self):
print( "Ring-ring!" )
def __turn_on(self):
self.__how_many_times_turned_on += 1
print( "Times was turned on: ", self.__how_many_times_turned_on )
m... |
f8b1dd75c2283fec69c9236c52814a3c7ae31396 | romanzdk/books-recommender | /processing.py | 987 | 3.671875 | 4 | import pandas as pd
df = pd.read_csv('data/out.csv', sep=';')
def get_similar(book_name):
author_books = []
year_books = []
# get all books with the corresponding name
books = (
df[df['title'].str.contains(book_name.lower())]
.sort_values('rating_cnt', ascending = False)
)
... |
7486bead68a7bf0c2e7d2a4ed289203a278be6b7 | bb-bb/KwantumNum | /task1.py | 1,557 | 3.5 | 4 | """
author: Geert Schulpen
Task 1; random disorder
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button
import random as random
g_AxColor = "lightgoldenrodyellow"
random.seed(1248)
def disorder(size,scale):
"""
A function that generates a disor... |
18e1e68ed464494e6547e83b3c827fb322ddfa89 | Yrshyx/C | /python/第一题.py | 237 | 3.734375 | 4 | counter=0
for i in range(1,5):
for j in range(1,5):
for k in range(1,5):
if i!=j and j!=k and i!=k:
print("{} {} {}".format(i,j,k))
counter +=1
print("共有{}种".format(counter))
|
507fdcb28060f2b139b07853c170974939267b63 | Abhinav-Rajput/CodeWars__KataSolutions | /Python Solutions/Write_ Number_in_Expanded_Form.py | 611 | 4.34375 | 4 | # Write Number in Expanded Form
# You will be given a number and you will need to return it as a string in Expanded Form. For example:
# expanded_form(12) # Should return '10 + 2'
# expanded_form(42) # Should return '40 + 2'
# expanded_form(70304) # Should return '70000 + 300 + 4'
def expanded_form(num):
strNum... |
41159eb6bd04eeaf5593014c6820fcf7e30b5832 | Abhinav-Rajput/CodeWars__KataSolutions | /Python Solutions/spyGames.py | 437 | 3.5625 | 4 | def decrypt(code):
z = {0: ' '}
sum = 0
res = ''
arr = []
for i in range(1, 27):
z[i] = chr(i + 96)
codes = code.split()
for c in codes:
for a in c:
if a.isdigit():
sum += int(a)
if sum > 26:
sum = sum % 27
arr.append(su... |
8d6538986282bfbe541fe6e1d4a0b36920072f78 | jgarciagarrido/tuenti_challenge_7 | /challenge_4/solve.py | 758 | 3.84375 | 4 | def is_triangle(a, b, c):
return (a + b > c) and (b + c > a) and (a + c > b)
def perimeter(triangle):
return triangle[0] + triangle[1] + triangle[2]
def min_perimeter_triangle(n, sides):
sides.sort()
triangle = None
for i in xrange(1, n-1):
b = sides[i]
c = sides[i+1]
for... |
6e71a0d9e1518351d493c96315b76817a7d0e214 | RickLee910/Leetcode_easy | /Array_easy/offer_16.py | 322 | 3.75 | 4 | class Solution:
#动态规划
def maxSubArray1(self, nums):
if nums == []:
return 0
else:
for i in range(1, len(nums)):
nums[i] = max(nums[i] + nums[i - 1], nums[i])
return max(nums)
sol = Solution()
a = [1,-1,-2,3]
print(sol.maxSubArray(a))
|
c6fe56f2f56e95e1c34fb75e533abc0917d46512 | RickLee910/Leetcode_easy | /Hash_easy/leetcode_349.py | 276 | 3.515625 | 4 | from collections import Counter
class Solution:
def intersection(self, nums1, nums2):
temp1 = Counter(nums1)
temp2 = Counter(nums2)
ans = []
for i in temp1.keys():
if temp2[i] >0:
ans.append(i)
return ans |
c8ad40f63b827bb6102c20bb82a510f35cd8a6bc | RickLee910/Leetcode_easy | /Array_easy/leetcode_88.py | 896 | 3.59375 | 4 | class Solution:
def merge(self, nums1, m, nums2, n):
for i in range(len(nums1)-m):
nums1.pop()
for j in range(len(nums2)-n):
nums2.pop()
nums1.extend(nums2)
nums1.sort()
def merge1(self, nums1, m, nums2, n):
temp = {}
temp1 = []
for... |
3b2c8b6e23b557a1f8013f8ed9750ea72b72e3f7 | RickLee910/Leetcode_easy | /String_easy/inter_01.09.py | 650 | 3.8125 | 4 | class Solution:
#切片比较
def isFlipedString(self, s1: str, s2: str) -> bool:
if len(s1) != len(s2):
return False
return s1 in (s2 + s2)
#循环判断
def isFlipedString1(self, s1: str, s2: str) -> bool:
if len(s1) != len(s2):
return False
if s1 == '' and s2 =... |
2eaa46e63db5e0cdec6028abf86595d8ebf0504d | RickLee910/Leetcode_easy | /Array_easy/inter_17.04.py | 261 | 3.53125 | 4 | import collections
class Solution:
def missingNumber(self, nums):
temp = collections.Counter(nums)
for i in range(len(nums) + 1):
if i not in temp:
return i
s = Solution()
a = [1,2,3,4,5]
print(s.missingNumber(a)) |
c58e8f35f2412cd9caf48ddb1330bf23bd631ee1 | RickLee910/Leetcode_easy | /Array_easy/leetcode_35.py | 626 | 3.703125 | 4 | class Solution:
#二分法
def searchInsert1(self, nums, target):
first, end = 0, len(nums)
while first < end:
mid = (first + end) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
first = mid + 1
else:
... |
b68eff085bc7ac20fa2fb7b462af20e511fdcf29 | satishky18/VM-reservation-system | /28sept2021542PM-vm-inventory.py | 3,796 | 3.78125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
class Machine:
"""A sample Employee class"""
def __init__(self, ip, username, password, avalible, owner):
self.ip = ip
self.username = username
self.password = password
self.avalible = avalible
self.owner = owner
# I... |
33f746a4c39d26398bed011515bcd32aef4630ab | ottohahn/OHNLP | /splitter/splitter.py | 1,365 | 3.84375 | 4 | #!/usr/bin/env python3
"""
A basic sentence splitter, it takes a text as input and returns an array of
sentences
"""
import re
INITIALS_RE = re.compile(r'([A-z])\.')
def splitter(text):
"""
Basic sentence splitting routine
It doesn't take into account dialog or quoted sentences inside a sentence.
"""
... |
a597c668dda0375e97dbe33b4dce6d1cc42a8a69 | kernel-memory-dump/UNDP-AWS-2021 | /16-ec2/test-program.py | 1,984 | 3.6875 | 4 | import program
failed_tests = []
pass_tests = []
def test_max1_handles_same_number_ok():
a = 2
result = program.max1(a, a)
if result == a:
pass_tests.append('test_max1_handles_same_number_ok PASSED')
else:
failed_tests.append(f'test_max1_handles_same_number_ok FAILED: the returned valu... |
b8ca7993c15513e13817fa65f892ebd014ca5743 | Satona75/Python_Exercises | /Guessing_Game.py | 816 | 4.40625 | 4 | # Computer generates a random number and the user has to guess it.
# With each wrong guess the computer lets the user know if they are too low or too high
# Once the user guesses the number they win and they have the opportunity to play again
# Random Number generation
from random import randint
carry_on = "y"
while... |
12c145181efc2ff5fba7113ad3be5dd4f8941369 | Satona75/Python_Exercises | /multiply_even_numbers.py | 210 | 3.96875 | 4 | def multiply_even_numbers(list):
evens = [num for num in list if num%2 == 0]
holder = 1
for x in evens:
holder = holder * x
return holder
print(multiply_even_numbers([1,2,3,4,5,6,7,8])) |
c069374b1d2c822c9a71b4c7c95ac5e7e3ca945f | Satona75/Python_Exercises | /RPS-AI.py | 1,177 | 4.3125 | 4 | #This game plays Rock, Paper, Scissors against the computer.
print("Rock...")
print("Paper...")
print("Scissors...\n")
#Player is invited to choose first
player=input("Make your move: ").lower()
#Number is randomly generated between 0 and 2
import random
comp_int=random.randint(0, 2)
if comp_int == 0:
computer... |
474ae873c18391c8b7872994da02592b59be369c | Satona75/Python_Exercises | /RPS-AI-refined.py | 1,977 | 4.5 | 4 | #This game plays Rock, Paper, Scissors against the computer
computer_score = 0
player_score = 0
win_score = 2
print("Rock...")
print("Paper...")
print("Scissors...\n")
while computer_score < win_score and player_score < win_score:
print(f"Computer Score: {computer_score}, Your Score: {player_score}")
#P... |
44cbdbc57f54a30a0c711991f5d57e93c369acb3 | moon0331/baekjoon_solution | /others/10809.py | 232 | 3.84375 | 4 | import string
word = input()
result = []
for c in string.ascii_lowercase:
result.append(word.find(c))
print(*result)
print(*[input().find(c) for c in string.ascii_lowercase])
# print(*map(input().find,map(chr,range(97,123)))) |
7c2e2524d3de22c2feb4f5551ced1318ca102f87 | moon0331/baekjoon_solution | /programmers/Level 1/약수의 합.py | 120 | 3.53125 | 4 | def solution(n):
return sum(x for x in range(1, n+1) if n%x == 0)
print(solution(12) == 28)
print(solution(5) == 6) |
c2464adf389dca62e0d39b969f16c6c4197f6f20 | moon0331/baekjoon_solution | /programmers/Level 2/[1차] 프렌즈4블록.py | 1,712 | 3.59375 | 4 | def reverse_board(board): # (m,n)
new_board = [line[::-1] for line in list(map(list, zip(*board)))]
return new_board # (n,m)
def search_pop_blocks(m, n, board): # board (m,n) 들어올때 지워야 할 인덱스와 지워지는 블록 수 반환 (reverse될때 확인 필요)
erase_idx = [set() for _ in range(n)]
pop_idx = set()
for i in range(m-1):
... |
19830dddda2ffb1971d0360f0634d69e1d05754d | moon0331/baekjoon_solution | /programmers/Level 2/문자열 압축.py | 1,281 | 3.5625 | 4 | def get_new_subword_info(word=None):
return {'word':word, 'n_freq':1, 'init':False}
def subword_info_to_string(subword_info):
if subword_info['n_freq'] >= 2:
return str(subword_info['n_freq']) + subword_info['word']
else:
return subword_info['word']
def solution(s):
if len(s) == 1:
... |
83ec2cd0ebe74f598b82553c40dfaa4c3c041a87 | moon0331/baekjoon_solution | /others/8958.py | 149 | 3.5625 | 4 | def nth(x):
x = len(x)
return int(x*(x+1)/2)
N = int(input())
for _ in range(N):
txt = input().split('X')
print(sum(map(nth, txt))) |
95a921ad3f8564b509fdbed54dabeab02b55eaea | moon0331/baekjoon_solution | /programmers/Level 1/정수 제곱근 판별.py | 145 | 3.5 | 4 | def solution(n):
sqrt = n**0.5
return int((sqrt+1)**2) if sqrt == int(sqrt) else -1
print(solution(121) == 144)
print(solution(3) == -1) |
f648b2f6240acb7757aaa42fa3a3adebb3edd9c0 | moon0331/baekjoon_solution | /level2/1259.py | 144 | 3.625 | 4 | while True:
num = input()
if num == '0':
break
print('yes' if all(map(lambda x: x[0]==x[1], zip(num, num[::-1]))) else 'no') |
f566d4798eb7ba166d80406eedbf310cca8f5350 | moon0331/baekjoon_solution | /programmers/Level 1/내적.py | 157 | 3.703125 | 4 | def solution(a, b):
return sum([x*y for x, y in zip(a,b)])
print(solution([1,2,3,4], [-3, -1, 0, 2]) == 3)
print(solution([-1, 0, 1], [1, 0, -1]) == -2) |
f61b06360de5642bc8df6c24371f0c5a2a8b58e1 | moon0331/baekjoon_solution | /programmers/고득점 Kit/전화번호 목록.py | 634 | 3.828125 | 4 | '''
가장 짧은 숫자의 자리수 : n
number[:n] 에서부터 number[:] 까지 hash값 담아버림
'''
def solution(phone_book):
phone_book.sort(key=lambda x:len(x))
print(phone_book)
for i in range(len(phone_book)-1):
subword = phone_book[i]
words_rng = phone_book[i+1:]
for word in words_rng:
if word.sta... |
ce5f9b82b4843c790112e72e2e9555ae29ead8ed | atikus/study1 | /mystudy/generator.py | 364 | 3.796875 | 4 | # bu fonk her yeni çağrılışında baştan başlıyor.
def deneme():
for i in range(5):
yield i*i*i
for j in deneme():
print(j)
for j in deneme():
print(j)
print("= "*40)
# bu bir kere kullanılıyor. ve kendini mem den siliyor.
generator = (x*x*x for x in range(5))
for j in generator:
print(j)
f... |
096e3e7959be263809b5f5c809e3a2e847771c19 | dkoriadi/query-plans-visualiser | /PlansFrame.py | 3,626 | 3.8125 | 4 | """
PlansFrame.py
This script is called by app.py to display multiple QEPs in tree format.
"""
import tkinter
import tkinter.scrolledtext
import MainFrame
class PlansPage(tkinter.Frame):
"""
This is the class that displays the plans page whereto view all possible QEPs. It is displayed as a
separate f... |
19dbab140d55e0b7f892d66f08b9dc26ba5f4095 | timurridjanovic/javascript_interpreter | /udacity_problems/8.subsets.py | 937 | 4.125 | 4 | # Bonus Practice: Subsets
# This assignment is not graded and we encourage you to experiment. Learning is
# fun!
# Write a procedure that accepts a list as an argument. The procedure should
# print out all of the subsets of that list.
#iterative solution
def listSubsets(list, subsets=[[]]):
if len(list) == 0... |
d5b4078fc05372736115f67ea8044976fe1ab994 | dundunmao/LeetCode2019 | /680. Valid Palindrome II.py | 672 | 3.765625 | 4 | # 问一个string是不是palindrome,可以最多去掉一个char
class Solution(object):
def validPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
l = 0
r = len(s)-1
while l < r:
if s[l] != s[r]:
return self.isPanlin(s,l,r-1) or self.isPanlin(s,l+1,r)
... |
71dda13cd5f310acf20845a091a5663b7fbee6f6 | dundunmao/LeetCode2019 | /long_qomolangma.py | 708 | 3.625 | 4 | def qomolangma(array):
start = 0
res = 1
for i in range(len(array)):
if array[i] < array[start]:
res = max(res, i - start + 1)
start = i
if start == len(array) - 1:
return res
new_start = len(array) - 1
for j in range(len(array) - 1, start - 1, -1):
... |
a0bb6c5c0a352812303e2dd732927dd21d487b6b | dundunmao/LeetCode2019 | /975. Odd Even Jump.py | 3,340 | 3.625 | 4 |
# 最后结果
import bisect
class Solution1:
def oddEvenJumps(self, A):
n = len(A)
odd_jump = [False] * n
even_jump = [False] * n
bst = SortedArray()
# base case
odd_jump[n - 1] = True
even_jump[n - 1] = True
bst.put(A[n - 1], n - 1)
# general case
... |
91fdacb3c856743643ffced2e2963efbb77224da | dundunmao/LeetCode2019 | /426. Convert BST to Sorted Doubly Linked List.py | 4,401 | 3.9375 | 4 | """
# Definition for a Node.
class Node(object):
def __init__(self, val, left, right):
self.val = val
self.left = left
self.right = right
"""
class Solution(object):
def treeToDoublyList(self, root):
"""
:type root: Node
:rtype: Node
"""
if not r... |
25f1ecffe70394a7cbaa66761d07d4f343301ab1 | dundunmao/LeetCode2019 | /1094. Car Pooling.py | 928 | 3.546875 | 4 | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
capacity_array = []
for trip in trips:
capacity_array.append(SeatCapacity(trip[0], trip[1], 1))
capacity_array.append(SeatCapacity(trip[0], trip[2], -1))
capacity_array.sort()
... |
234a66bc28e80b148b555449f8a8c581e06c9854 | dundunmao/LeetCode2019 | /139. word break.py | 8,985 | 3.5625 | 4 |
# 给出一个字符串s和一个词典,判断字符串s是否可以被空格切分成一个或多个出现在字典中的单词。
#
# 您在真实的面试中是否遇到过这个题? Yes
# 样例
# 给出
#
# s = "lintcode"
#
# dict = ["lint","code"]
#
# 返回 true 因为"lintcode"可以被空格切分成"lint code"
class Solution:
# @param s: A string s
# @param dict: A dictionary of words dict
def wordBreak(self, s, dict):
# write your... |
a935afab319838c30d5e68573bae93e95da04ae2 | dundunmao/LeetCode2019 | /587. Erect the Fence.py | 1,263 | 3.515625 | 4 | class Solution:
def outerTrees(self, points):
point_array = []
for p in points:
point = Point(p[0], p[1])
point_array.append(point)
point_array.sort()
point_stack = []
for i in range(len(point_array)):
while len(point_stack) >= 2 and self.... |
cdfacc797df7c4d29f48907b1719e1a36522d1d9 | dundunmao/LeetCode2019 | /703. Kth Largest Element in a Stream.py | 1,008 | 3.8125 | 4 | import heapq
class KthLargest:
def __init__(self, k, nums):
self.top_k_min_heap = []
self.size = k
i = 0
while i < len(nums) and k > 0:
heapq.heappush(self.top_k_min_heap, nums[i])
i += 1
k -= 1
while i < len(nums):
if self.top... |
dba0a491be622d41f73dd8c8b1294e2e2d0ad2fd | dundunmao/LeetCode2019 | /138 Copy List with Random Pointer .py | 4,754 | 3.625 | 4 |
class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solution:
# @param head: A RandomListNode
# @return: A RandomListNode
def copyRandomList(self, head):
# write your code here
if head is None:
return... |
04cd7500781232849379a93fe63a29a96daaf347 | dundunmao/LeetCode2019 | /212. Word Search II.py | 5,797 | 3.984375 | 4 | # class TrieNode:
# def __init__(self):
# self.flag = False
# self.s = ''
# self.sons = []
# for i in range(26):
# self.sons.append(None)
#
#
# class Trie:
# def __init__(self):
# self.root = TrieNode()
# def insert(self, word):
# # Write your code... |
d51ee8447c2680177bab81e87d626fe4bc567024 | dundunmao/LeetCode2019 | /449. Serialize and Deserialize BST.py | 1,680 | 3.734375 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
... |
c3192e3a235a580209903a4c70ee2b3c39978bde | dundunmao/LeetCode2019 | /124. Binary Tree Maximum Path Sum.py | 9,004 | 3.90625 | 4 | # 给出一棵二叉树,寻找一条路径使其路径和最大,路径可以在任一节点中开始和结束(路径和为两个节点之间所在路径上的节点权值之和)
#
# 您在真实的面试中是否遇到过这个题? Yes
# 样例
# 给出一棵二叉树:
#
# 1
# / \
# 2 3
# 返回 6
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
# 用resultTyoe这个class
class ResultType(object):
def __... |
87dd5e40f48b6154f4ad565ae45304307fb13144 | dundunmao/LeetCode2019 | /241. Different Ways to Add Parentheses.py | 1,309 | 4.0625 | 4 | # Given a string of numbers and operators, return all possible results from computing all the different
# possible ways to group numbers and operators. The valid operators are +, - and *.
#
#
# Example 1
# Input: "2-1-1".
#
# ((2-1)-1) = 0
# (2-(1-1)) = 2
# Output: [0, 2]
#
#
# Example 2
# Input: "2*3-4*5"
#
# (2*(3-(4... |
31df3f479fd5b5552b9a1396163008dc38abd9d6 | dundunmao/LeetCode2019 | /69. Sqrt(x).py | 1,323 | 3.859375 | 4 |
class Solution:
"""
@param x: An integer
@return: The sqrt of x
"""
def sqrt(self, x):
start = 1
end = x
while start+1 < end:
mid = start+(end-start)/2
if mid*mid <= x:
start = mid
else:
end = mid
i... |
e7ea9a45373e0021b745e8e19d441139163e36e8 | dundunmao/LeetCode2019 | /1123. Lowest Common Ancestor of Deepest Leaves.py | 1,116 | 3.765625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lcaDeepestLeaves(self, root: TreeNode) -> TreeNode:
res = Result()
self.dfs(root, 0, res)
return res.lca
... |
910a21d1d3d13cfbaccf71ea77218b06a375d7fb | dundunmao/LeetCode2019 | /test.py | 31,321 | 3.578125 | 4 | # def water_flower(a, capacity):
# res = 0
# left = capacity
# for i in range(len(a)):
# if a[i] > left:
# res += i * 2
# left = capacity - a[i]
# if left < 0:
# return -1
# else:
# left -= a[i]
#
# return res + len(a)
#
# d... |
016434f27aba32f18907f1c6918f17d48ab3d279 | dundunmao/LeetCode2019 | /71. Simplify Path.py | 2,223 | 3.609375 | 4 |
class Solution(object):
def simplifyPath(self, path):
#把每个有效路径存places里,不存‘ ’和‘.’
places = [p for p in path.split("/") if p!="." and p!=""]
stack = []
for p in places: #对于存好的每个ele
if p == "..": #如果是‘..'就从stack里pop一个ele。如果不是就往stack里压入一个ele
if len(stack)... |
ca29c23ac842885b8661bbd34e8fd6a20bb16d83 | dundunmao/LeetCode2019 | /381. Insert Delete GetRandom O(1) - Duplicates allowed.py | 2,717 | 3.890625 | 4 | from random import choice
class RandomizedCollection:
def __init__(self):
"""
Initialize your data structure here.
"""
self.randomized_hash = {}
self.array = []
def insert(self, val: int) -> bool:
"""
Inserts a value to the collection. Returns true if ... |
51db392efffbfbbc86b4c8557660896b884de512 | dundunmao/LeetCode2019 | /199. Binary Tree Right Side View.py | 1,876 | 3.640625 | 4 | class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
from collections import deque
from collections import deque
class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
... |
ce3c6173edd8573af176473a0de58b581553e2ad | dundunmao/LeetCode2019 | /128. Longest Consecutive Sequence.py | 2,078 | 3.75 | 4 | # Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
#
# For example,
# Given [100, 4, 200, 1, 3, 2],
# The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
#
# Your algorithm should run in O(n) complexity.
# 麻烦的做法
class Solution:
def longe... |
e23abce5463ea24cabd75aee1967d58369d52a85 | mattions/libNeuroML | /neuroml/examples/example5.py | 353 | 3.5 | 4 | """
This example shows how a morphology can be translated
such that the translated node moves to the new origin
and all other nodes move along with it
"""
import neuroml.morphology as ml
a=ml.Node([1,2,3,10])
b=ml.Node([4,5,6,20])
a.connect(b)
print a.morphology.vertices
b.translate_morphology([1,2,3])
print 'translat... |
6108ea4b42d7de0e4059c54d6402e01bc56ba9de | jacobfdunlop/TUDublin-Masters-Qualifier | /binaryToDecimal.py | 424 | 3.984375 | 4 | user_num = input("Please Enter a binary number: ")
length = int(len(user_num))
power = ()
x = int()
z = int()
output = int()
while length >= 0:
z = int(user_num[length - 1])
if z == 1:
power = (2 ** x) * z
x += 1
length -= 1
output += power
else:
... |
9a6487e077eeefcb009581a7d4ad31284a4b064c | jacobfdunlop/TUDublin-Masters-Qualifier | /strings18.py | 368 | 3.796875 | 4 | user_str = input("Please enter a word: ")
while user_str != ".":
vowels = "aeiou"
if user_str[0] in vowels:
print(user_str + "yay")
else:
for a in range(len(user_str) + 1):
if user_str[a] in vowels:
print(user_str[a:] + user_str[0:a] + "ay")
... |
912a424503a40ee722d387c7e36c42d89154e97f | jacobfdunlop/TUDublin-Masters-Qualifier | /3.py | 170 | 3.890625 | 4 | speed = int(60)
birthday = bool(False)
if birthday == True:
speed -= 5
if speed <= 60:
print(0)
elif speed <= 80:
print(1)
else:
print(2)
|
efd37abad30060a9c670221bdf1beabb24d2fc08 | jacobfdunlop/TUDublin-Masters-Qualifier | /2.py | 299 | 3.90625 | 4 | temp = int(95)
summer = bool(True)
if (temp >= 60) and (temp <= 90) and (summer == (False)):
party = bool(True)
print(party)
elif (temp >= 60) and (temp <= 100) and (summer == (True)):
party = bool(True)
print(party)
else:
party = bool(False)
print(party)
|
fe94c67660a68772c4905710f2cf33d746899a4c | jacobfdunlop/TUDublin-Masters-Qualifier | /7.py | 117 | 4.0625 | 4 | usernum = int(input("Please enter a number: "))
if usernum % 2 == 0:
print("Even")
else:
print("Odd")
|
c593ca80cbc671e86d12f8d2ffaf0829fdb024ea | jacobfdunlop/TUDublin-Masters-Qualifier | /10.py | 470 | 4.1875 | 4 | usernum1 = int(input("Please enter a number: "))
usernum2 = int(input("Please enter another number: "))
usernum3 = int(input("Please enter another number: "))
if usernum1 > usernum2 and usernum1 > usernum3:
print(usernum1, " is the largest number")
elif usernum2 > usernum1 and usernum2 > usernum3:
pri... |
0de459da4ba683c92fb56128f1eef870ab822c15 | jacobfdunlop/TUDublin-Masters-Qualifier | /calculator.py | 794 | 4.09375 | 4 |
check = bool(False)
while check == (False):
usernum1 = int(input("Please enter a number: "))
userop = str(input("Please enter an operator + - * or /: "))
usernum2 = int(input("Please enter a number: "))
if userop == "+":
answer = int(usernum1 + usernum2)
print(usernum1, ... |
5c98a2fc08bb815d3278866a9f32469c82a214cf | jacobfdunlop/TUDublin-Masters-Qualifier | /rev_secondword.py | 383 | 3.515625 | 4 | def reverse_second_word(user_str):
b = []
a = user_str.split(" ")
count = 0
for c in a:
if count % 2 != 0:
b.append(c[::-1])
count += 1
else:
b.append(c)
count += 1
print(' '.join(b))
string = "One thousand and e... |
952e2170cc98d6d104decc89a0b26267b340624f | udrea/interplanetary-rover | /rover/rover.py | 4,697 | 3.765625 | 4 | from typing import List, Tuple
class PlanetGrid:
"""Class responsible for setting up the planet grid
"""
def __init__(self, grid_size: Tuple[int, int]) -> None:
self.m, self.n = grid_size # number of rows/columns of grid
self.grid = self.generate_grid()
def generate_grid(self) -> List... |
ff7a1bc5e6f0020f7dcaf65aa68eb1fd2ccb676f | kirankumarnallamalli/firstPyProject | /Sampletest.py | 561 | 3.890625 | 4 | #list
l1=["apple","Banana",1250,5000.23,"Kumar"]
print(l1)
l1.append("kiran")
print(l1)
l1.remove("kiran")
print(l1)
print(len(l1))
l1.reverse()
print(l1)
l1.pop(4)
print(l1)
#Tuples
t1=("Kiran",122,178.78,"Kiran",True,1234.56)
print(t1)
for t2 in t1:
print(t2)
print(len(t1))
x=list(t1)
print(x)
x.append("John")
... |
1d4b232ce7be7260fd8dc317a2fdb9cf13a35aef | bllxue090/210CT-Coursework | /basic_7.py | 238 | 3.875 | 4 |
def check_prime(n, x):
if(n<=1):
return False
if(x>=n):
return True
if(n%x==0):
return False
return check_prime(n,x+1)
if __name__ == '__main__':
n = 47
print check_prime(n, 2)
|
10f606d6afdf608dd51aa2641237550b75070466 | cryptogeekk/cryptography | /ceaser_encryption.py | 675 | 4.03125 | 4 | text=' ABCDEFGHIJKLMNOPQRSTUVWXYZ'
key=3
def caesar_encrypt(plain_text):
cipher_text=''
plain_text=plain_text.upper()
for l in plain_text:
index=text.find(l)
index=(index+key)%len(text)
cipher_text=cipher_text+text[index]
return cipher_text
def caes... |
bf3011a8789935e977bf8f8965a53617627ffbe1 | abiodun0/amity-room-allocation | /tests/test_main.py | 5,083 | 3.84375 | 4 | import unittest
from models.people import *
from main import *
from models.room import *
class TestOfMainSpacesAllocation(unittest.TestCase):
"""
This are for testing the main.py class function and method
"""
def setUp(self):
"""
This is to setup for the rest of the testing the input
"""
self.andela = Buil... |
ebbb82d3b60fafbbd90fd254c7c813a99325b413 | KudoS1410/Fouriers | /p3.py | 2,021 | 3.671875 | 4 | """To make a moving point on a circle image"""
import cv2 as cv
import numpy as np
import math
import colorsys as cs
import random
page = np.zeros([512, 512, 3], np.uint8)
blank = page.copy()
time = 0
yplot = []
while True:
# reset the template each time we write a new screen
page = blank.copy... |
76425414b1d88727dc471850636025bccdfee408 | JackRDmacc/Final_Project | /ecommerce_project/Customer.py | 765 | 3.84375 | 4 | """Jack Reser
This program is an ecommerce store with a customer database and GUI
11/25/20"""
from ecommerce_project import Cart
class Customer:
"""class Customer"""
next_id = 1000
# Constructor
def __init__(self, fname, lname):
self.fname = fname
self.lname = lname
self.cust_... |
993a0e034aba9cacecf504b877490a63e876604f | eloybarbosa/Desenvolvimento-Python-para-Redes-e-Sistemas-Operacionais | /AT/06/Servidor.py | 1,482 | 3.84375 | 4 | """
Escreva um programa cliente e servidor sobre TCP em Python em que:
O cliente envia para o servidor o nome de um diretório e recebe a lista de arquivos (apenas arquivos) existente nele.
O servidor recebe a requisição do cliente, captura o nome dos arquivos no diretório em questão e envia a resposta ao cliente de vo... |
7bef7916f76ce70d2ca19e5899b6b4e9f479a878 | farheenzaman01/computational-principles-in-python | /Entrance trackerFarheenZaman1.py | 2,027 | 4.09375 | 4 | # I created a progra for a user to sign in using their name a
#program records the number of people each user is signing in
#Program detects if the building is exceeding capacity
#proogram signs out user out of the system
#prpgram reports the signed in people (min/max) by one user
#declaring the function to ask the us... |
06ed38941edbfc0f8d04c22ca71587b59b51df94 | farheenzaman01/computational-principles-in-python | /exam2.py | 2,699 | 4.03125 | 4 | #list created to store menue details
names = ['Coffee', 'Pizza', 'Burger', 'Fries', 'Donut']
costs = {"a":5.00, "b":6.00, "c":7.00, "d":8.00, "e":0}
status = {"default":"Confirmed", "a":"Prepared", "b":"On Delivery", "c":"Delivered", "d":"Cancelled"}
#following class and object is supposed to store the costs and name... |
d9951e117fe7cd6107403eb6f7631f778561e8aa | farheenzaman01/computational-principles-in-python | /GIFT CARD TACKER.FARHEEN.py | 2,141 | 3.75 | 4 | def addgiftcard(code, giftcard_dic):#storing gift card ammount to the assigned codes to create a new card
if code < 10000:
print("Invalid code")
return
elif code >= 50000:
c = "$5"
elif code in range(40000, 50000):
c = "$4"
elif code in range(30000, 40000):
c = "$... |
20cad7654cd9b3f27d9263d17bf10871e75442fc | YuriiSynyavskiy/PythonForBeginnersRofl | /class.py | 3,634 | 3.5625 | 4 |
'''
#1
def sered(*args):
sum = 0
for i in args:
sum+=i
return sum/len(args)
print(sered(10,20,30))
#2
def myAbs(number):
return number if number>0 else number*(-1)
print(myAbs(-2))
print(myAbs(-4))
print(myAbs(2))
#3
def max(var_1, var_2):'''
#docstring
'''
return v... |
9e8651c2be2e81b9260ff07ec4f1c69d3de4ecfe | Uther88/metabol | /metabol.py | 3,003 | 4 | 4 | #---------------------------------------------------------------------------------#
# Программа для расчета скорости метаболизма и количества необходимых калорий #
# для поддержания актуальной массы тела в течении суток, в зависимости от уровня #
# дневной активности ... |
267335a2b28e9bc77b99f0b288f5bbb6f5b4d763 | KelseySlavin/CIS104 | /Assignments/Lab1/H1P1.py | 524 | 4.15625 | 4 | first_name = input("What is your first name?: ")
last_name = input("What is your last name?: ")
age = int(input("What is your age?: "))
confidence=int(input("How confident are you in programming between 1-100%? "))
dog_age= age * 7
print("hello, " + first_name+ " " + last_name + " , nice to meet you! You might be " + s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.