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 |
|---|---|---|---|---|---|---|
2688f66ba9e38b00dac4c25532e6cca5af931c0b | gsy/leetcode | /level_order_traversal_reverse.py | 1,119 | 3.515625 | 4 | __author__ = 'guang'
__author__ = 'guang'
from bst import TreeNode
class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
>>> s = Solution()
>>> three, nine, twenty, fifty, seven = TreeNode(3), TreeNode(9), TreeNode(20), ... |
e94c8523946233ee9c2fc222a6ddbdad9be24f07 | gsy/leetcode | /third_maximum.py | 1,187 | 3.875 | 4 | # -*- coding: utf-8 -*-
class Solution:
def thirdMax(self, nums):
stack = []
remain = []
for num in nums:
if len(stack) == 0:
stack.append(num)
else:
while len(stack) > 0:
top = stack[-1]
if top... |
7b56902235095a797f4c8296a6e239eda45285cb | gsy/leetcode | /partition_list.py | 2,472 | 3.734375 | 4 | __author__ = 'guang'
from linklist import LinkedList, ListNode
class Solution(object):
def empty(self, ls):
head, tail = ls
return head is None and tail is None
def append(self, node, ls):
"""
>>> s = Solution()
>>> node = ListNode(3)
>>> head = LinkedList.from... |
e4911f942dec9139ff2e5604c35420fb74b40ac5 | gsy/leetcode | /expressive_words.py | 1,715 | 3.71875 | 4 | # -*- coding: utf-8 -*-
class Solution:
def stretchy(self, word, string):
# word -> string
index, prev, count, stretch, length = 0, None, 0, False, len(word)
for char in string:
if index < length and char == word[index]:
if stretch and count < 3:
... |
0173011b8fe6d564cf6cb99f5bce029910c40e8d | gsy/leetcode | /merge_sorted_arrays.py | 924 | 3.78125 | 4 | # -*- coding: utf-8 -*-
class Solution:
def merge(self, nums1, m, nums2, n):
"""
Do not return anything, modify nums1 in-place instead.
"""
last, i, j = m + n - 1, m - 1, n - 1
while last >= 0:
if i >= 0 and j >= 0:
if nums1[i] >= nums2[j]:
... |
a771c81613d8a54089018954a7c83496ece404e0 | gsy/leetcode | /shortest_completing_word.py | 1,086 | 3.828125 | 4 | # -*- coding: utf-8 -*-
import string
class Solution:
def word_count(self, word):
result = {}
for char in word:
char = char.lower()
if char in string.ascii_lowercase:
result[char] = result.get(char, 0) + 1
return result
def contains(self, curren... |
d1cb3c5f571f7cddd6683d95a90ae39febe5befe | gsy/leetcode | /word_subsets.py | 1,459 | 3.578125 | 4 | # -*- coding: utf-8 -*-
class Solution:
def word_count(self, word):
count = {}
for char in word:
count[char] = count.get(char, 0) + 1
return count
def all_is_subset(self, sets, word):
target = self.word_count(word)
sources = [self.word_count(item) for item ... |
734a867d6107a4687e080b736b74b68211808e5d | gsy/leetcode | /binarytree/bstToGst.py | 1,043 | 3.859375 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
acc = 0
class Solution:
def dfs(self, root):
global acc
if root is None:
return
if root.right:
self.dfs(root.righ... |
c24cec409a45b42544a6baf747d0d67353468248 | gsy/leetcode | /most_common_word.py | 959 | 3.6875 | 4 | # -*- coding: utf-8 -*-
class Solution:
def mostCommonWord(self, paragraph, banned):
count = {}
result, maximum = "", 0
p = ""
for char in paragraph:
if char in (["!", "?", "'", ",", ";", "."]):
p = p + " "
else:
p = p + char... |
15e93f299e567cc4f433fe691660ede5e0e05556 | gsy/leetcode | /rotate_array.py | 399 | 3.578125 | 4 | # -*- coding: utf-8 -*-
class Solution:
def rotate(self, nums, k):
length = len(nums)
tmp = nums[:]
for index, num in enumerate(nums):
new_index = (index + k) % length
nums[new_index] = tmp[index]
print(nums)
if __name__ == '__main__':
s = Solution()
... |
759b84866a1bdeb16c8d43607a696cf9f54bb03a | gsy/leetcode | /binarysearch/search.py | 1,511 | 3.953125 | 4 | # 段落内有序,所以在一个段落内是可以使用二分搜索的
# 怎样确定一个段落?从 left 往后找,知道第一个比 left 小的 item 为止,都是一个段落
# 一个段落一个段落搜索
class Solution:
def calculateRight(self, arr, length, left):
# 递增的尽头,需要的包含的关系
j = left + 1
if j >= length:
return length - 1
if arr[j] > arr[left]:
while j < length ... |
705c58a95afe2e0cca93ee1835e36762fcb10cb1 | gsy/leetcode | /divide_two_integers.py | 1,785 | 3.65625 | 4 | # -*- coding: utf-8 -*-
class Solution(object):
def to_result(self, sign, result):
if (sign == '+' and result > 2147483647) or (sign == '-' and result >= 2147483647):
return 2147483647
if sign == '+':
return result
else:
return -result
def divide(s... |
61a95ba036525853d05519c90d4f4611661258ba | gsy/leetcode | /symmetric_tree.py | 1,400 | 3.625 | 4 | __author__ = 'guang'
from bst import TreeNode
class Solution(object):
def is_mirror(self, tree_a, tree_b):
"""
>>> s = Solution()
>>> two, three, four = TreeNode(2), TreeNode(3), TreeNode(4)
>>> two.left, two.right = three, four
>>> another_two, another_three, another_four ... |
429b4db73aceb10f9e60088d84184c08b93d0709 | gsy/leetcode | /to_lowercase.py | 237 | 3.75 | 4 | # -*- coding: utf-8 -*-
class Solution:
def toLowerCase(self, text):
if len(text) == 0:
return ""
result = ""
for char in text:
result = result + char.lower()
return result
|
16813951845c110fc7016b6ffcbb4bf36e3bbd5e | gsy/leetcode | /character_bits.py | 395 | 3.734375 | 4 | # -*- coding: utf-8 -*-
class Solution:
def isOneBitCharacter(self, bits):
if len(bits) == 0:
return False
start, end = 0, len(bits)
while start < end:
if bits[start] == 1:
step = 2
start = start + step
else:
... |
8eba3c4f9088044d2b3dc3dc575ed7624d2fc474 | gsy/leetcode | /longest_word.py | 1,204 | 3.65625 | 4 | # -*- coding: utf-8 -*-
class Solution:
def longestWord(self, words):
words = sorted(words, key=len)
# print(words)
prefix = set()
result, maxlen = "", 0
for word in words:
length, flag = len(word), False
if length == 1:
prefix.add(w... |
a07ac46de56d67febbb9de4fc3f4d94fcbdfef16 | gsy/leetcode | /complex_number_multiply.py | 1,666 | 4 | 4 | # -*- coding: utf-8 -*-
class Complex(object):
def to_int(self, number):
if len(number) == 0:
return 0
else:
return int(number)
def virtual_to_int(self, virtual):
if len(virtual) == 0:
return 0
assert 'i' in virtual
virtual = virtua... |
b5c90ec12d927261e8646f2f012a5fa085a2e34e | gsy/leetcode | /h_index.py | 923 | 3.53125 | 4 | # -*- coding: utf-8 -*-
class Solution:
def hIndex(self, citations):
if len(citations) == 0:
return 0
citations = sorted(citations, reverse=True)
count, seen = {}, set()
acc = 0
for citation in citations:
if citation not in seen:
se... |
87ceba67fa4c7df94bd8b068917124ed2b9e0764 | gsy/leetcode | /magic_dictionary.py | 2,072 | 3.859375 | 4 | # -*- coding: utf-8 -*-
import string
class MagicDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.origin = {}
def buildDict(self, words):
"""
Build a dictionary through a list of words
"""
for word in words:
... |
c5d7c2e7628f882388b6f4824e5585a4ad5031dd | gsy/leetcode | /greatest_common_divisor_of_strings.py | 1,410 | 3.625 | 4 | # -*- coding: utf-8 -*-
class Solution:
def can_divide(self, string, pattern):
len_string = len(string)
len_pattern = len(pattern)
if len_string < len_pattern:
return False
elif len_string == len_pattern:
return string == pattern
elif len_string % le... |
7628da6b3b35602907c016486af3671a1c956b6e | gsy/leetcode | /binarysearch/minArray.py | 504 | 3.828125 | 4 | class Solution:
def minArray(self, numbers):
length = len(numbers)
left, right = 0, length - 1
while left < right:
mid = (left + right) // 2
if (mid-1 >= 0 and numbers[mid-1] > numbers[mid]) and\
(mid+1 < length and numbers[mid+1] > numbers[mid]):
... |
6723a4891900dea8926f5a5afec4b65af35b8209 | gsy/leetcode | /balanced_binary_tree2.py | 1,058 | 3.765625 | 4 | # -*- coding: utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 深度优先搜索,找到左右子树的深度
def bfs(self, node):
if node is None:
return 0
height = 0
level = [None, node]
while len(... |
1596f34fe89c8b494c33d86b9dfb4d3ed5218b7d | gsy/leetcode | /sum_of_two_integers.py | 752 | 3.734375 | 4 | # -*- coding: utf-8 -*-
class Solution:
def bit_plus(self, a, b, carry):
return (a ^ b) ^ carry, (a & b) | (a ^ b) & carry
def getSum(self, a, b):
digit, carry, result = 1, 0, 0
while True:
a_bit = a & digit
b_bit = b & digit
if a_bit == 0 and b_bit ... |
aff108b752d4c24402b491d8c16adebdf8e83c32 | gsy/leetcode | /remove_elements.py | 1,420 | 3.640625 | 4 | __author__ = 'guang'
from linklist import LinkedList
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
>>> s = Solution()
>>> head = LinkedList.fromList([1, 2, 6, 3, 4, 5, 6])
>>> result = s... |
3589234dc4866f58175ac0997900612b26810e0c | gsy/leetcode | /greedy/splitIntoFibonacci.py | 1,131 | 3.75 | 4 | class Solution:
def isValid(self, sub, result):
if sub[0] == '0':
if sub != '0':
return False
number = int(sub)
if number < 0 or number > 2**31 - 1:
return False
length = len(result)
if length >= 2:
if int(result[-2]) + i... |
3d6b32068849d5a9ba3710624939f2c005d248c5 | gsy/leetcode | /jewels_and_stones.py | 280 | 3.734375 | 4 | # -*- coding: utf-8 -*-
class Solution:
def numJewelsInStones(self, jewels, stones):
return len([stone for stone in stones if stone in jewels])
if __name__ == "__main__":
s = Solution()
r = s.numJewelsInStones("aA", "aAAbbbb")
print(r)
assert r == 3
|
0226034d87c72f4ae335dc4caec32a79ec3d81ef | gsy/leetcode | /number_of_segments_in_a_string.py | 439 | 3.8125 | 4 | # -*- coding: utf-8 -*-
class Solution:
def countSegments(self, s):
if s == '':
return 0
s = s.strip()
return len([word for word in s.strip().split(' ') if len(word) > 0])
if __name__ == '__main__':
s = Solution()
r = s.countSegments(", , , , a, eaefa")
as... |
9053cb3f263ebbd5abb09c8f2e3bb25f6dabc10f | miklo88/Python-Traversy | /functions.py | 787 | 3.890625 | 4 | # A function is a block of code which only runs when it is called. In python, we do not use curly brackets, we use indentation with tabs or spaces
# Create function
def sayHello(name):
print(f'Hola {name}')
sayHello('Carlitos')
# can also invoke function with no argument
def sayHello(name='Muchachicho'):
p... |
48554d61a2c6fb9ea934594ead8d9f9f3878e0af | prasadbhatane/Nesting_Software_and_Automated_Marker | /Nesting software/nesting.py | 624 | 3.6875 | 4 | from sheet import Sheet
from utils import insertRectangles, showNestedDiagram
n = int(input("Enter the number of rectangles : "))
input_rect = []
sheetLength, sheetBreadth = 0, 0
print('Enter length and breadth of each rectangle separated by space eg, : 100 20')
for i in range(n):
s = input("rect {} length... |
1933c18b415d81163a1062c572945fdbe68ef776 | Dmitrii-Geek/Homework | /lesson4.7.py | 256 | 3.65625 | 4 | from math import factorial
from itertools import count
def fibo_gen():
for el in count(1):
yield factorial(el)
x = 0
for i in fibo_gen():
print('Factorial {} - {}'.format(x + 1, i))
if x == 14:
break
x += 1 |
dddaff54b7253daf23b8affde8ecb78738525ea0 | binary-hideout/sistemas-adaptativos | /practica3/constantes.py | 699 | 3.625 | 4 | from numpy import ones, fill_diagonal
# crear matriz de numpy rellena con unos, de 6 x 6
feromonas = ones((6, 6), int)
# poner la diagonal principal en ceros
fill_diagonal(feromonas, 0)
# cambiar el tipo de la matriz a listas nativas de Python
feromonas = list([list(_) for _ in feromonas])
distancias = list()
# 0. Va... |
b86abe1335cb3bccf6ab9d37a61f2360d53db4f3 | canbula/wait_and_signal | /main.py | 1,535 | 3.734375 | 4 | import random
import time
from threading import Thread, Condition
class JobsAndUsers:
def __init__(self, number_of_users, number_of_resources, job_size):
self.n = number_of_users
self.r = number_of_resources
self.m = job_size
self.resources = [Condition() for _ in range(number_of_r... |
50ab8a86aebc87a51c24521aa58ded5812a7bb1c | kostadinov92/Python-Demo | /dicts.py | 1,190 | 4.0625 | 4 | temperatures = {
'София': -14,
'Новосибирск': -31,
'Таити': 30,
'Таити1': [30, 2],
'Варна': {22, 3},
'Русе': {
"temperature": -23,
"humidity": 90,
},
'ловдив': None,
'Пазарджик': None
}
print("-" * 20)
print(temperatures)
print(temperatures['София'])
print(temperatur... |
fc5cfcfae2c7e0a44cc29705b057c357bb8d143e | kostadinov92/Python-Demo | /mostCommonLetters.py | 1,325 | 3.75 | 4 | import math
MAX_LETTERS = 20
def collect_data(text: str) -> dict:
if not text:
raise ValueError('The text is empty.')
letters = {}
for ch in text.upper():
if ch.isalpha():
if ch not in letters:
letters[ch] = 0
letters[ch] += 1
return letters... |
28b37589581db73560df3b438c7101b7c08379c6 | BitScriptor/MetodosNumericos | /regresionLineal.py | 1,055 | 3.546875 | 4 | #!/usr/bin/python
from sympy import *
x = Symbol('x')
ejex=[]
ejey=[]
xmedia = 0.0
ymedia = 0.0
b1num = 0.0
b1den = 0.0
datosx = input("Cuantos datos insertaras?: ")
for i in range (0,datosx):
columna1 = input("Introduce el dato %d de la primer columna: " %i)
columna2 = input("Introduce el valor del dato anterior... |
e7b4fe817ae3bde42f8fa61638a4e1a8251c1086 | dongwookang95/PythonAndRubyPrac | /Practice14/practice14.py | 163 | 3.859375 | 4 | input = 33
real_andy = 11
real_abc = "ab"
if real == input:
print("hoe")
elif real_andy == input:
print("hey andy")
else:
print("you are not a hoe")
|
cdd2515c906f5e2d6baf680b81e63cbe8930d015 | ChrisChrisRivera/CS1-Lab | /main.py | 273 | 3.8125 | 4 | xValue= 20
while xValue>=10:
print(xValue)
xValue= xValue - .5
for i in range(25):
import math
print(math.sqrt(i))
vaild= False
while not vaild:
value= int(input("number please"))
if value > 0 and value < 100:
valid= True
else:
print("CORRECT!") |
15774b26dae087e6ec683e676046c29d2009b904 | devimonica/Python-exercises---Mosh-Hamedani-YT- | /4.py | 490 | 4.5 | 4 | # Write a function called showNumbers that takes a parameter called limit. It should
# print all the numbers between 0 and limit with a label to identify the even and odd numbers. For example,
# if the limit is 3, it should print:
# 0 EVEN
# 1 ODD
# 2 EVEN
# 3 ODD
# Solution:
def showNumbers(limit)... |
adbdfb2b999bdc80235f70a51e552491b4b96456 | Saurav-bit/Hacktober | /sum.py | 120 | 3.90625 | 4 | a=0
b=1
print(a,b)
n=int(input("enter a number"))
for i in range (n-2):
c=a+b
a=b
b=c
print(c)
|
30ac424917d40846e2e494400a194358a06578ef | StephanOn/Project1 | /Ausgabe.py | 272 | 3.65625 | 4 | # Datumsabfrage
print("Geben Sie ein Datum ein (TT.MM.JJJJ):")
x = input()
z = x[6] + x[7] + x[8] + x[9] + x[3] + x[4] + x[0] + x[1]
# Definition des Dateinamens
filename = z+".txt"
f = open(filename, "r")
# Ausgabe des Dateiinhalts
print(f.read())
|
77891051a793383d0ec33c5570cb1a0674dcd938 | jgeilers/nyt_spelling_bee_word_finder | /word_finder.py | 680 | 3.59375 | 4 | import sys
import json
## READS JSON FILE
with open(sys.argv[1], "r") as JSON:
json_dict = json.load(JSON)
letters, alph = sys.argv[2], "qwertyuiopasdfghjklzxcvbnm"
required, additional = letters[0], letters[1:]
## FOR JSON FILE WITH ALPHABET LETTERS AS KEYS AND
## WORDS CONTAINING THAT LETTER AS VALUES
common = s... |
ef5ff75446d45350e4c3399889891eab99db4b28 | marekbrzo/CodingPractice | /rotateArray.py | 428 | 3.703125 | 4 | def rotateArray(A,k):
if k == 0 or k == len(A):
return print(A)
elif k > len(A):
return print(A)
else:
output = []
output = A[-k:]
output.extend(A[0:-k])
return print(output)
rotateArray([1,2,3,4,5,6,7,8,9,10],2)
rotateArray([1,2,3,4,5,6,7,8,9,10],0)
rotateAr... |
d5d3b540482b581ad95e5a4d4ab4e8dbcc1280fd | gninoshev/SQLite_Databases_With_Python | /delete_records.py | 411 | 4.1875 | 4 | import sqlite3
# Connect to database
conn = sqlite3.connect("customer.db")
# Create a cursor
c = conn.cursor()
# Order By Database - Order BY
c.execute("SELECT rowid,* FROM customers ORDER BY rowid ")
# Order Descending
c.execute("SELECT rowid,* FROM customers ORDER BY rowid DESC")
items = c.fetc... |
3122c8fdebd7f0643e99d8132225f97aed98fe0f | sanjay19/gopal | /amstrongint.py | 205 | 3.546875 | 4 | y=int(input())
z=int(input())
for num in range(y,z):
order = len(str(num))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10
if num == sum:
print(num)
|
6ce623ff50e0e6c030bf8f53f2f2c43e2bafdfe2 | WerterHong/Machine-Learning-Algorithm-NLP | /code/binary_search.py | 521 | 3.5 | 4 | import sys
def binary_search(list, item):
low = 0
high = len(list) - 1
while low <= high:
mid = (low + high) // 2
guess = list[mid]
if guess == item:
return mid
if guess > item:
high = mid - 1
else:
low = mid + 1
return None
if __name__ == '__main__':
l... |
fc4353c5386b5d2497e0f1cfa7bd2d0503c7f1c1 | kaloyansabchev/Programming-Basics-with-Python | /05 While Loop Lab/02. Password.py | 151 | 3.53125 | 4 | username = input()
password = input()
new_password = input()
while new_password != password:
new_password = input()
print(f"Welcome {username}!") |
5a0637856f9dddcb3d6667340def81e831361c7d | kaloyansabchev/Programming-Basics-with-Python | /PB Exam - 20 and 21 February 2021/03. Computer Room.py | 755 | 4.25 | 4 | month = input()
hours = int(input())
people_in_group = int(input())
time_of_the_day = input()
per_hour = 0
if month == "march" or month == "april" or month == "may":
if time_of_the_day == "day":
per_hour = 10.50
elif time_of_the_day == "night":
per_hour = 8.40
elif month == "june" or month == ... |
9c9e6b4602f9b5df1273b9d42b2972276a32b104 | kaloyansabchev/Programming-Basics-with-Python | /PB Exam - 20 and 21 February 2021/02. Spaceship.py | 445 | 3.90625 | 4 | import math
width = float(input())
lenght = float(input())
high = float(input())
astronaught_h = float(input())
rocket_s = width * lenght * high
room_s = (astronaught_h + 0.4) * 2 * 2
persons = rocket_s / room_s
persons = math.floor(persons)
if persons <= 2:
print(f"The spacecraft is too small.")
elif 3 <= person... |
a818501d5eccec65ef65fe2d1cf461258ade1e99 | kaloyansabchev/Programming-Basics-with-Python | /03 Conditional Statements Advanced Lab/11. Fruit Shop.py | 1,773 | 4.125 | 4 | product = input()
day = input()
quantity = float(input())
if day == "Saturday" or day == "Sunday":
if product == 'banana':
banana_cost = 2.70 * quantity
print(f'{banana_cost:.2f}')
elif product == 'apple':
apple_cost = 1.25 * quantity
print(f'{apple_cost:.2f}')
elif product ... |
422e3e5875226f17df321bfa3b7b568a57ac361b | kaloyansabchev/Programming-Basics-with-Python | /PB Exam - 6 and 7 July 2019/04. Renovation.py | 703 | 3.71875 | 4 | import math
wall_h = int(input())
wall_w = int(input())
percentage_wp = int(input()) # част която няма да се боядисва
total_area = wall_h * wall_w * 4
area_for_painting = total_area - (total_area * percentage_wp / 100)
while True:
painted = input()
if painted == "Tired!":
print(f"{math.ceil(area_for_... |
a743f255baf631681fd5c9b3d2c95d8d7ba07d34 | kaloyansabchev/Programming-Basics-with-Python | /PB Exam - 28 and 29 March 2020/03. Energy Booster.py | 3,582 | 3.84375 | 4 | fruit = input()
size = input()
quantity = int(input())
if fruit == "Watermelon":
if size == "small":
small_W_price = quantity * 2 * 56
if small_W_price < 400:
print(f'{small_W_price:.2f} lv.')
elif 400 <= small_W_price <= 1000:
final_price = small_W_price - small_W_p... |
b4ef7e9dc074915ea667f55af0b95f81618b93ae | kaloyansabchev/Programming-Basics-with-Python | /PB - More Exercises/Simple Operations and Calculations/05. Training Lab.py | 208 | 3.640625 | 4 | import math
w = float(input())
h = float(input())
height = h * 100 - 100
h_desk = math.floor(height / 70)
wide = w * 100
w_desk = math.floor(wide / 120)
total_desks = h_desk * w_desk - 3
print(total_desks) |
1fac4c4ecff8b35c4290f3080edd14464cf6140a | kaloyansabchev/Programming-Basics-with-Python | /05 While Loop Lab/09. Moving.py | 381 | 3.8125 | 4 | width = int(input())
lenght = int(input())
hight = int(input())
volume = width * lenght * hight
command = input()
while command != 'Done':
boxes = int(command)
volume -= boxes
if volume <= 0:
print(f'No more free space! You need {abs(volume)} Cubic meters more.')
break
command = inpu... |
3af6201978625babdf6f693331cc09b65b8054bc | kaloyansabchev/Programming-Basics-with-Python | /04 For Loop Lab/08. Number sequence.py | 313 | 3.84375 | 4 | import sys
numbers = int(input())
bigger_n = -sys.maxsize
smaller_n = sys.maxsize
for n in range(1, numbers+1):
number = int(input())
if number < smaller_n:
smaller_n = number
if number > bigger_n:
bigger_n = number
print(f'Max number: {bigger_n}')
print(f'Min number: {smaller_n}') |
d21876b84f4f1b0c5548e785e8c9ce1cafa55615 | kaloyansabchev/Programming-Basics-with-Python | /PB - More Exercises/Simple Operations and Calculations/06. Fishland.py | 433 | 3.515625 | 4 | mackerel_price = float(input())
caca_price = float(input())
bonito_kg = float(input())
horse_mackerel_kg = float(input())
mussels_kg = float(input())
bonito_price = mackerel_price * 1.6
horse_mackerel_price = caca_price * 1.8
sum_bonito = bonito_price * bonito_kg
sum_horse_mackerel = horse_mackerel_price * horse_macke... |
9a6a0e05d1e457673a032e4806b051a67e68c612 | kaloyansabchev/Programming-Basics-with-Python | /03 Conditional Statements Advanced Lab/04. Personal Titles.py | 869 | 3.953125 | 4 | # 4. Обръщение според възраст и пол
# Да се напише конзолна програма, която прочита възраст (реално число) и пол ('m' или 'f'), въведени от
# потребителя, и отпечатва обръщение измежду следните:
# • "Mr." – мъж (пол 'm') на 16 или повече години
# • "Master" – момче (пол 'm') под 16 години
# • "Ms." – же... |
e48d2ef1b48c79abd6ce8e422e29e70da3db6d0b | kaloyansabchev/Programming-Basics-with-Python | /PB Exam - 28 and 29 March 2020/06. Tournament of Christmas.py | 780 | 3.765625 | 4 | days = int(input())
money_won = 0
total_wins = 0
total_loses = 0
for day in range(1, days+1):
result = input()
money_won_per_day = 0
wins = 0
loses = 0
while result != "Finish":
result = input()
if result == "win":
wins += 1
money_won_per_day += 20
el... |
a5d9d23300010113265e515b094ea70e482283f3 | kaloyansabchev/Programming-Basics-with-Python | /PB Exam - 18 and 19 July 2020/01. Agency Profit.py | 435 | 3.8125 | 4 | company = input()
tickets_adult = int(input())
tickets_kids = int(input())
ticket_price = float(input())
fee = float(input())
kid_t_price = ticket_price * 0.3
tickets_adult_total = ticket_price + fee
tickets_kids_total = kid_t_price + fee
total_t_price = tickets_adult_total * tickets_adult + tickets_kids_total * ticke... |
3d5213bbc4c322cf07f2bd4c2814d5fcd772f6d2 | kaloyansabchev/Programming-Basics-with-Python | /03 Conditional Statements Advanced Exercise/06. Operations Between Numbers.py | 746 | 4.0625 | 4 | n1 = int(input())
n2 = int(input())
operatora = input()
result = 0
result_type = ''
if n2 == 0 and operatora == '/' or n2 == 0 and operatora == '%':
print(f"Cannot divide {n1} by zero")
quit()
if operatora == '+':
result = n1 + n2
elif operatora == '-':
result = n1 - n2
elif operatora == '*':
res... |
10ab4f1dcd7a222356255a18de53c248e15445c9 | moreirab/nfml-quizzes | /estatistica-descritiva-2/investimentos.py | 611 | 3.6875 | 4 | import math
def calc_variance(dataset):
mean = sum(dataset)/len(dataset)
variances = []
for value in dataset:
variances.append((value - mean)**2)
variance = sum(variances)/len(dataset)
return variance
def calc_std(variance):
return math.sqrt(variance)
def print_spread(dataset):
va... |
49db4a8b1194738347865c019d9b4964b91d5dd8 | creatoryoon/CSE2003_1_2021_1_Sogang_- | /실습/제출/[실습12-2]120210198_윤동성_2.py | 520 | 3.875 | 4 | import math
bottle = []
def vol():
pi = math.pi
bottle.append(bottle[1]*pi*(bottle[0]**2))
bottle.append((bottle[2]/bottle[3])*100)
bottle[3] = round(bottle[3], 2)
bottle[4] = round(bottle[4], 2)
if bottle[4] > 100:
bottle.append("overflow")
else:
bottle.append("")
... |
3635376bd58b8f471349f69ff5f6c630c03b3d71 | creatoryoon/CSE2003_1_2021_1_Sogang_- | /실습/제출/[4장-1]120210198_윤동성_2.py | 275 | 3.71875 | 4 | s1 = "2021"
s2 = "03"
s3 = "21"
n1 = 12345.12345
n2 = 54321.54321
print("(1) Today is {}/{}/{}" .format(s1, s2, s3))
print("(2) n1={}, n2={}" .format(n1, n2))
print("(3) n1={:!^40.3f}" .format(n1))
print("(4) n2={:15.3e}" .format(n2))
print("(5) n1={:%<10.2f}" .format(n1))
|
a464fedd911ba308f7fab2b30b2e02a1ecd4abf6 | creatoryoon/CSE2003_1_2021_1_Sogang_- | /실습/9장 실습_3-1.py | 404 | 3.875 | 4 | N = int(input("Enter N (0 < N < 10) : "))
#error 출력
if N >= 10 or N <= 0 :
print("ERROR: N must be 0 < N < 10.")
else :
for i in range(1, N+1) :
for j in range(1, i+1) :
print(j, end="")
print()
Lines = N
if N % 2 == 1 :
Lines = N - 1
for i in range(Lines, 0, -1) ... |
cb257b3f1ee94fcd8e8ab82e07b2114695d6aba4 | creatoryoon/CSE2003_1_2021_1_Sogang_- | /실습/제출/[실습7-2]120210198_윤동성_1.py | 301 | 4.0625 | 4 | st1 = input("Enter the first string:")
st2 = input("Enter the second string:")
st1 = list(st1)
st2 = list(st2)
if sorted(st1) == sorted(st2):
print("%s, %s is anagram." %(str(''.join(st1)),str(''.join(st2))))
else :
print("%s, %s is not anagram." %(str(''.join(st1)),str(''.join(st2))))
|
9d1b60ecdd080b18c5fda1c16624595d257834bd | creatoryoon/CSE2003_1_2021_1_Sogang_- | /실습/7장 실습_2-1.py | 330 | 3.953125 | 4 | input1_ = input('Enter the first string:')
input2_ = input('Enter the second string:')
input_1 = list(input1_)
input_2 = list(input2_)
if (sorted(input_1) == sorted(input_2)) and (len(input_1) == len(input_2)):
print(input1_, ',', input2_, 'is anagram.')
else:
print(input1_, ',', input2_, 'is not anagram... |
acb1feb9d8441bbb0b69f7cf508bb1db2b724e50 | creatoryoon/CSE2003_1_2021_1_Sogang_- | /실습/제출/[실습9-2]120210198_윤동성_2.py | 243 | 3.875 | 4 | n1, n2 = map(int, input("Enter N1, N2(0 < N1 <= N2) : ").split())
n3 = 0
for i in range(n1, n2+1):
if (i % 2) == 0 :
n3 = n3 + i
else :
continue
print("Sum of even numbers between %d and %d is %d." %(n1, n2, n3))
|
5c23970b9349d03185d474b8e99fb917e2de5904 | creatoryoon/CSE2003_1_2021_1_Sogang_- | /실습/제출/[실습12-1]120210198_윤동성_3.py | 692 | 4.03125 | 4 | def operation(in1):
ft1, ft2, ft3 = in1.split()
ft1 = float(ft1)
ft3 = float(ft3)
result = 0
flag = 0
if ft2 == "+":
result = ft1 + ft3
elif ft2 == "-":
result = ft1 - ft3
elif ft2 == "*":
result = ft1 * ft3
elif ft2 == "/":
if ft3 == 0:
f... |
98b2c8fc5aede334d9e12ed1ba0ae7147036b3e2 | creatoryoon/CSE2003_1_2021_1_Sogang_- | /실습/제출/[실습9-1]120210198_윤동성_3.py | 115 | 3.734375 | 4 | s = "Sogang University"
print("original_s:", s)
for i in range(len(s)-1, -1, -1):
print(s[i], end="")
print()
|
d736d5e63095c4835179669dc6c32309190faf29 | creatoryoon/CSE2003_1_2021_1_Sogang_- | /실습/제출/[추가3]120210198_윤동성_3.py | 484 | 3.609375 | 4 | flag = True
def strfind(strs):
if len(strs) == 0:
global flag
flag = False
big = 0
small = 0
for i in strs:
if i.islower() == True:
small = small + 1
if i.isupper() == True:
big = big + 1
return big, small
n1, n2 = strfind... |
9fce05d95b44709ad7cdd9ec998969cf622786e0 | creatoryoon/CSE2003_1_2021_1_Sogang_- | /실습/제출/[실습12-3]120210198_윤동성_3.py | 2,632 | 3.90625 | 4 | student = [["name", "mid", "final", "grade"]]
def menu1():
info = list(input("이름 중간 기말 성적 입력:").split())
if len(info) == 3:
names = set()
if len(student) > 1:
for i in range(1, len(student)):
names.add(student[i][0])
if info[0] in names:
print("이... |
7e51aaadada9158e4049e1d7b3f9f060b51db255 | i-fernandez/Project-Euler | /Problem_047/problem_47.py | 1,354 | 3.546875 | 4 | """
Find the first four consecutive integers to have four distinct prime
factors each. What is the first of these numbers?
"""
from math import sqrt
def is_prime_from_list(n):
global prime_list
if len(prime_list) == 0:
return True
for p in prime_list:
if n%p == 0:
return False... |
00748cd7fff30c9aa50b89a0e72f454fd510dd33 | i-fernandez/Project-Euler | /Problem_014/problem_14.py | 742 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 30 13:18:25 2020
@author: israel
The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Which starting number, under one million, produces the longest chain?
"""
def get_sequence(num... |
3c13523aef62492df2bb4ed85a28d6b4924f93b5 | i-fernandez/Project-Euler | /Problem_035/problem_35.py | 991 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 6 18:24:43 2020
@author: israel
The number, 197, is called a circular prime because all rotations
of the digits: 197, 971, and 719, are themselves prime.
How many circular primes are there below one million?
"""
def is_prime_number(n):
... |
44b081ed32f22ae2fc0f5cebfaeab6fd1bf85390 | i-fernandez/Project-Euler | /Problem_005/problem_5.py | 1,392 | 3.90625 | 4 | """
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
"""
# Primeros 4 numeros primos
primes = [2,3,5,7]
# Obtiene una lista con los factores de un numero
def get_factors(n):
if n in primes:
return [int(n)]
else:
#print(f'Calling with n={n}')
... |
cd4df12309cf4c0b7b4aa9dfa093404c356084f6 | i-fernandez/Project-Euler | /auxiliary.py | 1,932 | 3.5 | 4 |
# Devuelve true si n es primo (sin conocimiento previo)
def is_prime_number(n):
if n < 2:
return False
end = int(n**0.5)
for i in range(2, end+1):
if n%i == 0:
return False
return True
# Devuelve true si n es primo
# Se apoya en prime_list, que contiene los primos descubier... |
86fc473e69d613957f64071f74deccb56705e5e0 | i-fernandez/Project-Euler | /Problem_037/problem_37.py | 986 | 3.984375 | 4 | """
Find the sum of the only eleven primes that are both truncatable
from left to right and right to left.
"""
def is_prime_number(n):
if n < 2:
return False
start = int(n**0.5)
for i in range(start, 1, -1):
if n%i == 0:
return False
return True
def all_primes(numbers):
... |
3b46d280e7581cb9cf36098bf3375b126a9305b7 | i-fernandez/Project-Euler | /Problem_004/problem_4.py | 862 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 27 19:32:24 2020
@author: israel
Find the largest palindrome made from the product of two 3-digit numbers.
"""
def is_palindrome(number):
st = str(number)
size = len(st)
for i in range(0,int(size/2)):
if (st[i] != st[size-i-1]... |
8d8679553a6740ffd22e782108d22493ee3c652b | i-fernandez/Project-Euler | /Problem_055/problem_55.py | 849 | 3.953125 | 4 | """
A number that never forms a palindrome through the reverse and add process is called a Lychrel number.
How many Lychrel numbers are there below ten-thousand?
"""
def is_palindrome(number):
st_n = str(number)
st_r = ''
for i in range(len(st_n)-1,-1,-1):
st_r += st_n[i]
return st_n == st_r
... |
bb2ff59d2062a5b6ab007782f05653c2fd7fb1c1 | Ramya74/ERP-projects | /Employee.py | 1,296 | 4.25 | 4 | employees = [] #empty List
while True:
print("1. Add employee")
print("2. Delete employee")
print("3. Search employee")
print("4. Display all employee")
print("5. Change a employee name in the list")
print("6. exit")
ch = int(input("Enter your choice: "))
if ch is None:
print("no data present in Employees")... |
8bac12f24d04003cb824c7242c9f77102ac8118b | notveryfamous/python-project1 | /number 布尔类型.py | 538 | 4.09375 | 4 | # 布尔类型是数字分类下的一种
print (int (True));
print (isinstance (True,int));
print (isinstance (False,int));
print (bool(1));
print (bool(0));
print (bool(-1));# 在数字类型下,布尔类型为0时,返回False
#布尔值总结
#当布尔值为0、None、空值时,布尔返回类型为False
print (bool(0));
print (bool(None));
print (bool());
print (bool(''));
print (bool(' '));#字符串... |
d7ec0d578c12d6fa8fca8924d7b4565bc5ebc2de | Ruymelo10/CursoemvideoPy | /exercicios/mundo2/ex69.py | 735 | 3.5625 | 4 | cont = maior = homem = novinha = 0
while True:
cont+=1
print('-'*40)
idade = int(input(f'Digite a idade da {cont}ª pessoa: '))
sexo = ' '
while sexo not in 'fFmM':
sexo = str(input('Digite o sexo desta pessoa[F/M]: ')).strip().upper()
if idade > 18:
maior +=1
if sexo == 'M':
... |
2fcb3f5d3ade699a7aac7c8eeb93acd714f3d0f8 | Ruymelo10/CursoemvideoPy | /exercicios/mundo3/ex95.py | 1,226 | 3.75 | 4 | lista_jogadores = list()
while True:
nome = str(input('Nome do jogador: '))
partidas = int(input('Quantas partidas ele jogou? '))
aproveitamento = list()
for i in range(1, partidas+1):
gols = int(input(f'Quantos gols na partida {i}? '))
aproveitamento.append(gols)
totalgols = sum(apr... |
da4ad75ecdf8263e72c7c1159cea4a22e84c353f | Ruymelo10/CursoemvideoPy | /exercicios/mundo2/ex41.py | 309 | 3.90625 | 4 | from datetime import date
ano = int(input('Digite seu ano de nascimento: '))
idade = date.today().year - ano
print('Sua categoria é: ')
if idade > 20:
print('Master')
elif idade > 19:
print('Senior')
elif idade > 14:
print('Junior')
elif idade > 9 :
print('Infantil')
else:
print('Mirim') |
902cb1c5600f00391d9967678cec9721119666ca | Ruymelo10/CursoemvideoPy | /exercicios/mundo3/ex100.py | 450 | 3.625 | 4 | from random import randint
def sorteio(lista):
print(f'Sorteando 5 valores da lista: ',end='')
for i in range(0,5):
x= randint(1,10)
lista.append(x)
print(f'{x} ', end='', flush=True)
print('PRONTO!')
def somaPar(lista):
soma=0
for i in lista:
if i % 2 == 0:
... |
08ec291cd7b1d00b008385ba689d4840667736ba | Ruymelo10/CursoemvideoPy | /exercicios/mundo3/ex78.py | 656 | 3.5625 | 4 | lista =[]
maior = 0
menor = 999999
for i in range(0,5):
lista.append(int(input(f'Digite um numero para a posição {i}: ')))
if i ==0:
maior=menor=lista[i]
else:
if lista[i] > maior:
maior = lista[i]
if lista[i] < menor:
menor = lista[i]
print('=-'*20)
print(f'... |
29bf78bab98dc250f497fc8b1f72adbdaa36b9dc | Ruymelo10/CursoemvideoPy | /exercicios/mundo3/ex104.py | 392 | 3.796875 | 4 | def leiaint(msg):
bol = False
value = 0
while True:
x = str(input(msg))
if x.isnumeric():
value = int(x)
bol = True
else:
print('\033[0;31mErro! Digite um número inteiro válido\033[m')
if bol:
break
return value
n = leiain... |
772271882a27bb4d660e2af47ab455b585e846a3 | Ruymelo10/CursoemvideoPy | /exercicios/mundo2/ex52.py | 266 | 4.03125 | 4 | num = int(input('Digite um numero: '))
bool = True
for i in range(num,0,-1):
if i!=num and i!=1:
if num%i==0:
bool=False
if bool == False:
print('O numero {} não é primo'.format(num))
else:
print('O numero {} é primo'.format(num)) |
4cbe2b7aefea9a5e38e2d69f55a1507ec14c9a65 | Aishwaryasri15/Python | /Hangman.py | 3,398 | 3.859375 | 4 | import random
import string
def hangman():
word =random.choice(["pugger","littlepugger","monkey","lemon","tamarind"
,"apple","mango","fruits","ginger","tiger","thor",
"avengers","ironman"])
validletters=string.ascii_lowercase
turns=10
guessmade=''
while len(word)... |
6e6a6cb235727ad6ea5a10bc0a44043d3260f444 | jonsongoffwhite/AlgorithmsCoursework | /Coursework_2/CW2-1 Sampling.py | 10,630 | 4 | 4 |
# coding: utf-8
# # Algorithms 202: Coursework 2 Task 1: Random Sampling
# Group-ID: 32
# Group members: Jonathan Muller, Louis de Beaumont, Jonny Goff-White
# ## Objectives
# The aim of this coursework is to enhance your algorithmic skills by developing algorithms from textual, non-formal descriptions. You are a... |
2552aff90c999eaa5435e856ee47700c32fc2161 | Vicky-hyq/pratice | /pratice/one test one day/文件相关操作/文字竖排/test.py | 1,261 | 3.515625 | 4 | #!/usr/bin/python
# -*- coding:utf-8 -*-
# coding:utf-8
import sys
stops = '!,。'
stops = stops.decode('utf-8')
print stops
def getLength(poe):
situation = [i for i in range(len(poe)) if poe[i] in stops]
situation.insert(0,-1)
print situation
gaps = [situation[i]-situation[i-1] for i in range(1,len(situation))]
... |
53708d31b2a96e02795a299fed1c1a017c13fe8b | Vicky-hyq/pratice | /pratice/one test one day/输出乘法表/test.py | 264 | 3.578125 | 4 | #!/usr/bin/python
# -*-coding:utf-8 -*-
'''
i = 1
for m in range(1,10):
while (i <= m):
s = i*m
print ("%d * %d = %d"%(i,m,s))
i = i+1
i = 1
'''
#参考答案更加简洁
for i in range(1,10):
for j in range(1,i+1):
print ("%d * %d = %d"%(j,i,j*i))
|
65bcba9f6366ad8091cfbb4dd2f53dc4af0fd85c | DaeseungLee/devops-eng-training | /unittest/test_functions.py | 682 | 3.53125 | 4 | # TODO(everyone): 더하기, 빼기, 곱하기, 나누기 함수 테스트 케이스 작성
import sys, os
from functions import plus, sub, multiplication, divide, square, sqrt
import pytest
def test_plus():
assert plus(3,4) == 7
assert plus(132,145) == 277
def test_sub():
assert sub(3,4) == -1
assert sub(120, 120) == 0
def test_multiplicat... |
6a40a28665f8194dc44ebb1fe4b43e80c59614a3 | elgrian/Tweet-Generator | /HistogramLists.py | 825 | 3.5625 | 4 | import re
frequency = {}
first_list = []
second_list = []
document_text = open('frankenstein.txt', 'r')
text_string = document_text.read().lower()
match_pattern = re.findall(r'\b[a-z]{1,15}\b', text_string)
for word in match_pattern:
count = frequency.get(word, 0)
frequency[word] = count + 1
first_list.... |
79342a6f9022af2503d7f0396a7226ff1a9dbaa5 | jke-zq/my_lintcode | /Intersection of Two Linked Lists.py | 778 | 3.71875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param headA: the first list
# @param headB: the second list
# @return: a ListNode
def getIntersectionNode(self, headA, headB):
# Write your co... |
a5969e2abbe3bdb906c39937617558dab5b6dff3 | jke-zq/my_lintcode | /Largest Rectangle in Histogram.py | 874 | 3.640625 | 4 | class Solution:
"""
@param height: A list of integer
@return: The area of largest rectangle in the histogram
"""
def largestRectangleArea(self, height):
# write your code here
if not height:
return 0
length = len(height)
stack = []
ans = f... |
a4234de4dcd883365be5796b61b3086e138acbfe | jke-zq/my_lintcode | /Interleaving String.py | 1,203 | 3.875 | 4 | class Solution:
"""
@params s1, s2, s3: Three strings as description.
@return: return True if s3 is formed by the interleaving of
s1 and s2 or False if not.
@hint: you can use [[True] * m for i in range (n)] to allocate a n*m matrix.
"""
def isInterleave(self, s1, s2, s3):
#... |
b7f6423314f8b6b884b6da63344c1491c503eda4 | jke-zq/my_lintcode | /Merge k Sorted Arrays.py | 3,015 | 3.75 | 4 | ## list optimization
class Solution:
# @param {int[][]} arrays k sorted integer arrays
# @return {int[]} a sorted array
def mergekSortedArrays(self, arrays):
# Write your code here
## 3 solution
def merge(list1, list2):
if not list1:
return list2
... |
8481e78392bdfdd7d9cbc52831c10946d68fe2c8 | jke-zq/my_lintcode | /Palindrome Linked List.py | 1,186 | 3.84375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a boolean
def isPalindrome(self, head):
# Write your code here
def reverse(root):
cu... |
2018146ed44187d36ed69a9b84395af772e413a8 | jke-zq/my_lintcode | /Data Stream Median.py | 1,112 | 3.671875 | 4 | import heapq
class Solution:
"""
@param nums: A list of integers.
@return: The median of numbers
"""
def medianII(self, nums):
# write your code here
if not nums:
return []
maxlen, minlen = 0, 0
maxheap, minheap = [], []
ans = []
... |
8aba59376aac59f1f9e0b6bc6083239d816c3f3b | jke-zq/my_lintcode | /Search in a Big Sorted Array.py | 1,025 | 3.84375 | 4 | """
Definition of ArrayReader:
class ArrayReader:
def get(self, index):
# this would return the number on the given index
# if there is no number on that index, return -1
"""
class Solution:
# @param {ArrayReader} reader: An instance of ArrayReader
# @param {int} target an integer
# @re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.