blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
7a6ad9b37c7c7771e06cf0e98e0aa4790af2e811 | aravindrrs/PractiseDsAlgo | /Stack.py | 998 | 3.953125 | 4 | #Stack Implementation
#pop, peek, return size, empty check , push
class Stack :
def __init__(self):
self.container = [] #initiating a list which is my stack holder
def push (self, item):
return self.container.append(item)
def sizecheck(self):
r... |
4b9cd03e6fa42f218989747bc09502a25a2bd77c | LiteWorm/wormlearning | /Python/基础/01_Python基础/ea_07_买苹果增强版.py | 185 | 3.796875 | 4 | price_str = input("苹果的单价:")
weight_str = input("苹果的重量:")
price = float(price_str)
weight = float(weight_str)
money = price * weight
print("总金额:", money)
|
47d121058714a6e349391feab14f3faccd10692a | jianyuhe/image_processing | /project/submit/Text_Extration_project/for_text_image.py | 8,059 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Nov 1 14:00:30 2019
Project Title: Text extraction.
Project Objective: Extract text in images
Team Members: Yuwei Chen, Minhui Chen, Jianyu He
"""
'''
Progrm description
This program will extract text from text image (like screen capture from what's up,screen captu... |
9396efd0fc39794fd114904dee6171c517e71590 | ldnicolasmay/RunestonePythonDS3 | /src/Chapter04/hot_potato.py | 634 | 3.609375 | 4 | from typing import List
from adt.queue import Queue # works
def hot_potato(names_list: List[str], num: int) -> str:
names_q = Queue()
for name in names_list:
names_q.enqueue(name)
while names_q.size() > 1:
print(f"This round's participants: {names_q}")
for i in range(num):
... |
bb690a63d854b800588540aa4e0d76d89943d4e6 | ldnicolasmay/RunestonePythonDS3 | /src/Chapter04/adt/stack.py | 1,020 | 3.953125 | 4 | import warnings
from typing import Any
class Stack(object):
"""Stack implementation as a list"""
def __init__(self) -> None:
"""Create new stack"""
self._items = []
def __str__(self) -> str:
return str(self._items)
def __repr__(self) -> str:
return repr(self._items)
... |
4182f4f549156f3b90fa906fffcfb6dcf794dbe8 | baoyf4244/interviews | /leetcode/back_tracking/0046_permutations.py | 536 | 3.578125 | 4 | from typing import List
class Solution:
def __init__(self):
self.res = []
def permute(self, nums: List[int]) -> List[List[int]]:
track = []
self.back_track(track, nums)
return self.res
def back_track(self, track, nums):
if len(track) == len(nums):
self... |
175b7189220d0778d35ad3017a8b83e5a7f8e3f5 | baoyf4244/interviews | /leetcode/dynamic_programming/0097_interleaving_string.py | 1,420 | 3.671875 | 4 | # class Solution:
# def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
# if len(s1) + len(s2) != len(s3):
# return False
#
# dp = [[False for _ in range(len(s2) + 1)] for _ in range(len(s1) + 1)]
# dp[0][0] = True
# for i in range(0, len(s1) + 1):
# fo... |
641187e08b671b33ec97db91145fcef096055c56 | baoyf4244/interviews | /leetcode/tecent/0002_add_two_numbers.py | 1,080 | 3.734375 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
cur1 = l1
cur2 = l2
results = ListNode(0)
results_cur = re... |
a764505f0526c461f9641c18022af7255cc7481f | baoyf4244/interviews | /coding_interviews/29_clockwise_print_matrix.py | 282 | 3.515625 | 4 | from typing import List
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
m = len(matrix)
n = len(matrix[0])
results = []
for i in range(m):
for j in range(n):
results.append(matrix[i][j]) |
48fb03d2dce942d32e81d5a83a1f2aeb6ae7f127 | baoyf4244/interviews | /coding_interviews/04_search_matrix.py | 635 | 3.8125 | 4 | from typing import List
class Solution:
def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
if not matrix:
return False
m = 0
n = len(matrix[0]) - 1
while n >= 0 and m < len(matrix):
if matrix[m][n] == target:
retur... |
768d1d82c7a5e66ae74876d31d525eb58627d66a | loristron/PythonExercises | /ChuteONumero/chute_o_numero_COD.py | 505 | 3.953125 | 4 | #Cria Algoritimo que gera um valor aleatório e tenho que ficar tentando até acertar
import random as rd
resposta = rd.randint(0, 100)
print(resposta)
acerto = False
while acerto == False:
tentativa = int(input("\nTente acertar o numero que pensei: "))
if tentativa == resposta:
print("Parabéns, você ace... |
bef559ed6bd7e6c9b3c1fbe1d9c96e04d6c606da | Kamakshi1997/NLP | /Sentiment.py | 544 | 3.59375 | 4 | #/usr/bin/python3
from textblob import TextBlob
import matplotlib.pyplot as plt
get_data="hello i am happy because its a beautiful day."
get_data2=" today i am watching a movie but its a bad movie."
get_data3=" i did not liked the movie. how are you?"
#for i in get_data :
#i.split()
analysis=TextBlob(get_data)
analysis... |
01262a0e937cf1ac384312a7e85c867b58f16f15 | jerry3links/leetcode | /DifficultyEasy/sol155MinStack.py | 832 | 4 | 4 | """
from DifficultyEasy.sol155MinStack import MinStack
obj = MinStack()
obj.push(-2)
obj.push(0)
obj.push(-3)
a = obj.getMin()
print("getMin(): {}".format(a))
obj.pop()
print("pop ...")
a = obj.top()
print("top: {}".format(a))
a = obj.getMin()
print("getMin(): {}".for... |
2fbd05f2d06d1910a6772ca06fe7932412475385 | jerry3links/leetcode | /DifficultyMedium/sol033SearchRotSortedArr.py | 1,008 | 3.609375 | 4 | """
from DifficultyMedium.sol033SearchRotSortedArr import Solution
nums = [4,5,6,7,0,1,2]
target = 0
ans = Solution().search(nums, target)
print(ans)
"""
class Solution:
def search(self, nums, target, rotated = True):
"""
:type nums: List[int]
:type target: int
:r... |
c3654660f83b11ca369509ab9184cf2805e73aa3 | jerry3links/leetcode | /DifficultyMedium/sol785IsBipartite.py | 931 | 3.5625 | 4 | """
from DifficultyMedium.sol785IsBipartite import Solution
graph = [[1,3], [0,2], [1,3], [0,2]]
graph = [[1,2,3],[0,2],[0,1,3],[0,2]]
ans = Solution().isBipartite(graph)
print(ans)
"""
class Solution:
def isBipartite(self, graph):
"""
:type graph: List[List[int]]
:rty... |
d23c461f98b5d3c18f730d2fe2b06cd1410184c3 | jerry3links/leetcode | /BinaryTree/solE108SortedArr2BT.py | 885 | 3.75 | 4 | """
from BinaryTree.solE108SortedArr2BT import Solution
nums = [-10,-3,0,5,9]
print("nums: {}".format(nums))
ans = Solution().sortedArrayToBST(nums)
print("Tree: ")
Solution().printTree(ans)
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self... |
083927c25fafb7b1507c75d1704eec0e81cd6519 | jerry3links/leetcode | /DifficultyEasy/solE263UglyNumber.py | 650 | 3.75 | 4 | """
from DifficultyEasy.solE263UglyNumber import Solution
num = 6
print("num: {}".format(num))
ans = Solution().isUgly(num)
print("ans: {}".format(ans))
"""
class Solution(object):
def isUgly(self, num):
"""
:type num: int
:rtype: bool
"""
if num <= 0:
... |
b537613e96b66b992ea0c8ccf1091f8fc6eef0d9 | jerry3links/leetcode | /DP/solE070ClimbingStairs.py | 529 | 3.625 | 4 | """
from DP.solE070ClimbingStairs import Solution
input = 2
print("input: {}".format(input))
ans = Solution().climbStairs(input)
print("ans = {}".format(ans))
"""
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n <= ... |
7df42295592fad20189c636b2da7620ae5eeda21 | jerry3links/leetcode | /DifficultyMedium/solM039CombSum.py | 2,157 | 3.5 | 4 | """
from DifficultyMedium.solM039CombSum import Solution
candidates = [2,3,6,7]; target = 7
print("candidates: {}; target: {}".format(candidates, target))
ans = Solution().combinationSum(candidates, target)
print(ans)
"""
# Note: all possible sets (not number of sets)
class Solution(object):
de... |
70952a7767cd7463708bb901010c7b6a079ff1dc | jerry3links/leetcode | /DifficultyEasy/sol896MonoArr.py | 1,246 | 3.640625 | 4 | """
from DifficultyEasy.sol896MonoArr import Solution
A = [1,2,2,3]
A = [1, 1, 1, 2, 2, 3, 2, 1]
A = [1, 1, 1, 2, 2, 3]
# A = [1, 1, 1, 2]
# A = [1, 1, 1]
print(A)
ans = Solution().isMonotonic(A)
print("ans: {}".format(ans))
"""
class Solution:
def isMonotonic(self, A):
... |
68e39cdf158fdbf9e6cc3e942010e3b34c1ae35b | SSJLL/AI-Classwork | /BFS_Assignment/sudoku.py | 11,114 | 4.21875 | 4 | import math
import os.path
from copy import deepcopy
"""This is where the problem is defined. Initial state, goal state and other information that can be got from the problem"""
class Problem(object):
def __init__(self, initial, size, horizontalChunks, verticalChunks, goal = ""):
"""This is the constructor for ... |
f99813ff9abc50fe2d13d1d33aa4eb975c41193d | daniel36933/repositorio-2 | /GuessTheNumber.py | 586 | 3.859375 | 4 | import random
numero = random.randrange(1,7)
guess = int (input("Adivina el número entre el 1 al 7: "))
var = 0
while guess != numero:
if guess < numero:
print("Este no es el número. Prueba con otro")
guess = int (input("\nAdivina el número entre el 1 al 7: "))
var = var + 1
else:
... |
9283b5231d080ef52ec9daa54e2a90dbfaf8d3be | ethmai/PythonBootCamp | /Methods-Functions.py | 475 | 3.71875 | 4 | # methods
l = [1, 2, 3, 3, 4, 5, 6]
print l
print l.count(3)
help(l.count)
"""functions
def sample_function(arg1, arg2):
pass
sample_function(1, 2)
"""
def addition(arg1, arg2):
"""
Usage: perform a addition for 2 integer
:rtype: object
:param arg1: number 1
:param arg2: number 2
:ret... |
3782e05672742de49dff28f96795201b56609d56 | ethmai/PythonBootCamp | /SetsNBooleans.py | 165 | 3.609375 | 4 | #Sets and Booleans
x = set()
x.add(1)
x.add(2)
x.add(1)
print x
l = [1,1,1,1,1,1,2,2,2,2,3,3,3,3,3,4,4,4,4,5,5,5,6]
set(l)
print set(l)
#Booleans
print bool(1>2)
|
667932c2d62153e17c5ba2b315d20c2b42c6e189 | khaidzir/seq2seq | /utility/timehelper.py | 601 | 3.875 | 4 | '''
-------------------- TIME RELATED HELPER FUNCTION --------------------
helper function for time related operation (mainly used for logging)
----------------------------------------------------------------------
'''
import time
import math
# converting second to minute
def asMinutes(s):
m = math.floor(s / 60... |
cba9fc0be7ceac96322cd48fd8a0f125bc0f8c77 | DavidALlbaHernandez/taller4Esc | /4.2.py | 184 | 3.765625 | 4 | """
#entradas
valor de rango-->int--->lista
#salidas
valor de la lista--->int--> divisibles de (i%7)
"""
lista=[]
for i in range(1,101):
if(i%7!=0):
lista.append(i)
print(lista) |
460869ed9b3a55851efbd3eb176417c713b2b53d | louispaulromero/Cal_State_Monterey_Bay | /2.CST_205_Multimedia_Design_&_Programming/project1-master/initialCompletedProject.py | 4,344 | 3.578125 | 4 | #Date Last Modified: February 3, 2016
#Temporal Median Filter On a Series of Images
def createPicture():
#MUST CALL SET MEDIA PATH TO SPECIFIY LOCATION OF IMAGES
setMediaPath()
#MUST CALL SET MEDIA PATH TO SPECIFIY LOCATION OF IMAGES
#CREATES MULTIPLE VARIABLES EACH CONTAINING SPECIFIED IMAGE
firstImageF... |
c0ecd5780a7c93bd3283f03c311af21caac404ca | ronny-souza/Lista-Exercicios-03-Python | /Exercicio07.py | 679 | 4.0625 | 4 | # QUESTÃO 07 - Faça um programa que receba a idade de várias pessoas e que para cada uma, calcule e mostre:
# - a quantidade de pessoas com idade maior ou igual a 18;
# - a quantidade de pessoas com idade menor que 18.
idade = 0
continuar = "Sim"
maiores18 = 0
menores18 = 0
quantidadePessoas = 0
while continuar.upper... |
e1ece4c4d42c095ba564edba820e960dbdb5a296 | atrox3d/udemy-python39 | /06-strutture-di-codice/048-list-comprehension.py | 262 | 3.875 | 4 | """
[expression for item in iterable if condition]
"""
numbers = [n for n in range(1, 10)]
print(numbers) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
quadratiDispari = [n * n for n in numbers if n % 2 == 1]
print(quadratiDispari) # [1, 9, 25, 49, 81]
|
99cad22a293b23f25b9aceeb1372961f65d69678 | suyeony0/Junior2ndSemester | /py/ForDeepLearning/stepFunc.py | 358 | 3.71875 | 4 | import numpy as np
import matplotlib.pyplot as plt
def step_function(x):
#y=x>0
#return y.astype(np.int)
return np.array(x>0,dtype=np.int)
'''x = np.arange(-5.0,5.0,0.1) # -5.0부터 5.0 까지 0.1의 간격으로 원소를 만들고 리스트에 담음
y= step_function(x)
plt.plot(x,y)
plt.ylim(-0.1,1.1) # y축의 범위 지정
plt.show()'''
|
73e5fe8378f605a3fb149a6e8b0697d40f13139f | dnddnjs/code_interview | /Hackerrank/dp_coin_change.py | 603 | 3.96875 | 4 | """ dynamic programming : coin change
author : Woongwon Lee
problem : https://www.hackerrank.com/challenges/ctci-coin-change/problem
output : Print a single integer denoting the number of ways we can make change
for dollars using an infinite supply of our types of coins.
"""
def make_change(coins, n):
lookup = [... |
62e9a94e27bfa4e9c09d6a27285aebf36a4a77ce | dnddnjs/code_interview | /Hackerrank/array_left_rotation.py | 675 | 3.796875 | 4 | """ arrays : left rotation
author : Woongwon Lee
problem : https://www.hackerrank.com/challenges/ctci-array-left-rotation/problem
output : Print a single line of n space-separated integers denoting the final
state of the array after performing d left rotations.
"""
def array_left_rotation(a, n, k):
new_array = []
... |
e6b1692f3611b9b31c29a4899f68dfe64fe14f09 | andyashall/blackjack-py | /main.py | 2,085 | 3.625 | 4 | from random import shuffle
deck = (list(range(2,11)) + ['Ace', 'King', 'Queen', 'Jack']) * 4
def main():
shuffle(deck)
ph, d = addCard([], deck)
dh, d1 = addCard([], d)
game(d1, dh, ph)
def game(d, dh, ph):
if evalHand(ph):
if evalHand(dh):
print(f'Dealers hand: {printHand(dh)}')
print(f'Yo... |
1c0a3f1019a66c84c4bb2663f8246a71ff23db45 | MarcHowe/TestPythonCode | /userInfo.py | 423 | 4.0625 | 4 | # Ask a user their name and tell them some things about themself
userName = input("What is your name?")
userAge = input("How old are you?")
userAgeInt = int(userAge)
print("Hello there " + userName)
userAgeTenTime = userAgeInt * 10
print("Your age times ten is " + str(userAgeTenTime))
if (userAgeInt >= 18):
pri... |
7faed0b956b9deed96afd9d5a82125b2e50f3dbf | akraycek/recovering-incomplete-monero-mnemonic | /discover_mnemonics.py | 5,945 | 3.859375 | 4 | '''
Discover Mnemonics
Includes all the functions and information necessary to discover a mnemonic when there are words missing.
This will search for any number of missing words. WARNING: one or two words is reasonable, but the search space grows
very rapidly.
Assumes a 13 word mnemonic.
'''
import json
import binas... |
637a0de429b81c1c42ca728f887f0bf7a7606d30 | RamiBenchouia1/AdventOfCode2020 | /day1/solution2.py | 825 | 3.578125 | 4 | import os
import sys
def answer(inputFile):
with open(os.path.join(sys.path[0], inputFile), "r") as f:
expenseReport = [int(line.strip()) for line in f.readlines()]
#nested for loop to add every possible combination of two numbers in the list, find its complement (to sum to 2020) and see if that compl... |
b7bdff3a5a9043d42ec3dd26c63c67c239f1b3cf | traj1593/LINEAR-PREDICTION-PROGRAM | /linearPrediction-tRaj-00.py | 1,173 | 4.25 | 4 | '''
Program: LINEAR PREDICTION
Filename: linearPrediction-tRaj-00.py
Author: Tushar Raj
Description: The program accepts two integers from a user at the console and uses them to predict the next number in the linear sequence.
Revisions: No revisions made
'''
### Step 1: Announce, prompt and get response
#Anno... |
f012b8e833a2871c3da252185ad47110bc754027 | alanrwhitley64/PythonTrainingMVA | /HelloWorld/readCSV.py | 429 | 3.703125 | 4 | def main():
import csv
with open('osdRFsched.csv', 'r') as myCSV:
CSVdata = csv.reader(myCSV)
for currRow in CSVdata:
#prints with [] list format first
print(currRow[0])
#then prints individual items separated by commas with the []
print(', '.join(currRow))
re... |
05c557692092b846f456ca3c33a1db417620ad07 | alanrwhitley64/PythonTrainingMVA | /HelloWorld/errorMessage.py | 598 | 3.921875 | 4 | def main():
import csv
import sys
myFile = input("Please enter the CSV file name to be read and written - ")
try :
with open(myFile, 'r') as myCSV:
CSVdata = csv.reader(myCSV)
for currRow in CSVdata:
print(', '.join(currRow))
print("Success!!!"... |
5cfbe157ea8047100b4ff532405b167c0aad685f | williamboco21/datastructures | /lists_01.py | 597 | 3.78125 | 4 | fruit = 'Banana'
try:
fruit[0] = 'b'
except:
print("String is immutable. Therefore, it cannot be changed.\n")
print(fruit.lower())
numbers = ['Asta', 'Shinra', 'Midoriya', 2, 4, 12, 63, 21]
for number in numbers:
if str(number):
name = number
print(f"Hello there, {name}!")
else:
... |
23a5c3ac4f2a1bf80ce62ae2d2a470412eefd849 | youjingdike/big-data-demo | /python-2.7/com/xq/script2/py_07_exceptions.py | 480 | 3.75 | 4 | # --coding:utf-8--
# 异常的捕获
# try:
# float('abc')
# except Exception, e:
# print e
#
# print "hello world"
# try:
# float(1)
# except Exception, e:
# print e
# finally:
# print 'Do not forget to close database.'
# try:
# assert 1 == 0
# print "hello"
# except AssertionError, err:
# ... |
2ba97f41d21e3364766dfc1da158e3566fa9b8f6 | lmcosta98/ia_functional_programing | /aula1.py | 2,795 | 3.515625 | 4 | #Exercicio 1.1
def comprimento(lista):
if lista == []:
return False
return 1 + comprimento(lista[1:])
#Exercicio 1.2
def soma(lista):
if lista == []:
return 0
if len(lista) > 0:
return lista[0] + soma(lista[1:])
#Exercicio 1.3
def existe(lista, elem):
if lista[0] == elem:
return True
return existe(list... |
4add73ede0452a77a46ae6301a974052f52ac2dc | HeimerR/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/8-uppercase.py | 212 | 4.03125 | 4 | #!/usr/bin/python3
def uppercase(str):
for i in range(len(str)):
a = str[i]
aux = chr(ord(a) - 32) if (ord(a) > 96 and ord(a) < 123) else a
print('{}'.format(aux), end='')
print()
|
42fd723316a51442c22fb676a3ec9f12ae82056b | HeimerR/holbertonschool-higher_level_programming | /0x0B-python-input_output/7-save_to_json_file.py | 302 | 4.125 | 4 | #!/usr/bin/python3
"""module
writes an Object to a text file
"""
import json
def save_to_json_file(my_obj, filename):
""" writes an Object to a text file, using a JSON representation"""
with open(filename, encoding="utf-8", mode="w") as json_file:
json_file.write(json.dumps(my_obj))
|
40613415e7f0649443aec73ea2837931f59fce92 | HeimerR/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/2-uniq_add.py | 252 | 3.765625 | 4 | #!/usr/bin/python3
def uniq_add(my_list=[]):
if my_list is not None:
sum = 0
my_list.sort()
for i in my_list:
while my_list.count(i) > 1:
my_list.remove(i)
sum += i
return sum
|
1ecbb83d5fb75b3f6f79440f1a83bb4cdbefb131 | AlyMetwaly/python-scripts | /python-code-challenges/03 Sort a String/my_sort_words.py | 344 | 4.09375 | 4 | def sort_words(phrase):
#split the words
words = phrase.split()
print(words)
#append a lowercase version of the word for each word
words = [w.lower() + w for w in words]
print(words)
words.sort()
words = [w[len(w)/2:] for w in words]
print(words)
return ' '.join(words)
if __name__ == '__main__':
print(sort_... |
3d0037321e46bd2a9e7a7a63f42d2744d85b00a2 | hatlonely/leetcode-2018 | /python/136_single_number.py | 254 | 3.5 | 4 | #!/usr/bin/env python3
class Solution:
def singleNumber(self, nums):
n = 0
for num in nums:
n ^= num
return n
if __name__ == '__main__':
solution = Solution()
print(solution.singleNumber([2, 2, 1]), 1)
|
05d413316325692851630df88239a93d7862a1af | hatlonely/leetcode-2018 | /python/933_number_of_recent_calls.py | 518 | 3.53125 | 4 | # !usr/bin/env python3
class RecentCounter:
def __init__(self):
self.ts = []
def ping(self, t):
i = 0
while i < len(self.ts):
if t - self.ts[i] <= 3000:
break
i += 1
self.ts = self.ts[i:]
self.ts.append(t)
return len(sel... |
0897f9cdece0d7ab6bdea2e0ad7204f267c4f44f | hatlonely/leetcode-2018 | /python/150_evaluate_reverse_polish_notation.py | 829 | 3.796875 | 4 | #!/usr/bin/env python3
class Solution:
def evalRPN(self, tokens):
stack = []
for token in tokens:
if token in {'+', '-', '*', '/'}:
num2 = stack.pop()
num1 = stack.pop()
if token == '+':
stack.append(num1 + num2)
... |
e99515829c083543e8b9033eb5dace44a744a7e5 | hatlonely/leetcode-2018 | /python/120_triangle.py | 694 | 3.515625 | 4 | #!/usr/bin/env python3
class Solution:
def minimumTotal(self, triangle):
if not triangle:
return 0
totals = [triangle[0]]
for i in range(1, len(triangle)):
total = [totals[i - 1][0] + triangle[i][0]]
for j in range(1, len(triangle[i]) - 1):
... |
7afc24fe24f49c34f016f0db36396069b49aa171 | hatlonely/leetcode-2018 | /python/143_reorder_list.py | 1,077 | 3.65625 | 4 | #!/usr/bin/env python3
from listnode import *
class Solution(object):
def reorderList(self, head):
if head is None or head.next is None:
return
slow = head
fast = head
while True:
if fast.next is None or fast.next.next is None:
break
... |
9a12556be695a6478844bd3fc3f3b0c626ce105b | hatlonely/leetcode-2018 | /python/122_best_time_to_buy_and_sell_stock_ii.py | 304 | 3.53125 | 4 | #!/usr/bin/env python3
class Solution:
def maxProfit(self, prices):
m = 0
for i in range(1, len(prices)):
m += prices[i] - prices[i-1] if prices[i] > prices[i-1] else 0
return m
if __name__ == '__main__':
print(Solution().maxProfit([7, 1, 5, 3, 6, 4]), 7)
|
0480adde53d0fb8b8b2f30e247d21cb41233d224 | bmihovski/PythonFundamentials | /reverse_string.py | 138 | 4.0625 | 4 | """
Write a program that reads a string from the console, reverses it and prints the result back at the console.
"""
print(input()[::-1])
|
e5666f5f6d68cc0fbc6d57012f6b9c3e740a09a8 | bmihovski/PythonFundamentials | /count_odd_numbers_list.py | 429 | 4.15625 | 4 | """
Write a program to read a list of integers and find how many odd items it holds.
Hints:
You can check if a number is odd if you divide it by 2 and check whether you get a remainder of 1.
Odd numbers, which are negative, have a remainder of -1.
"""
nums_odd = list()
nums_stdin = list(map(int, input().split('... |
75637b47970dfaad2df714cff0e1c40161164537 | bmihovski/PythonFundamentials | /products.py | 5,379 | 3.9375 | 4 | from pickle import dump, load
"""
You have been tasked to create a File Database for several stocked products at a universal shop.
A product has a Type (string), Name (string), Price (decimal) and Quantity (integer).
The type of the product can be - "Food", "Electronics", "Domestics".
The name of the product may consi... |
d03229593c9e605f31320e0200b0b258e191acee | bmihovski/PythonFundamentials | /sign_of_int_number.py | 581 | 4.25 | 4 | """
Create a function that prints the sign of an integer number n.
"""
number_stdin = int(input())
def check_int_type(int_to_check):
"""
Check the type of input integer and notify the user
:param int_to_check: Int
:return: message_to_user: Str
"""
if int_to_check > 0:
msg_to_user = f'T... |
f6a011b92ee7858403ea5676b01610ff962e1c0d | bmihovski/PythonFundamentials | /wardrobe.py | 2,079 | 4.21875 | 4 | """
On the first line of the input, you will receive n - the number of lines of clothes,
which came prepackaged for the wardrobe.
On the next n lines, you will receive the clothes for each color in the format:
" "{color} -> {item1},{item2},{item3}…"
If a color is added a second time, add all items from it and count th... |
2f0a2ccdbb1b6fe90e9c9a469884b07667837465 | bmihovski/PythonFundamentials | /person_info.py | 137 | 3.90625 | 4 | name = input()
age = input()
city = input()
wage = input()
print(f'{name} is {age} years old, is from {city} and makes ${float(wage)}')
|
a2a1ac3fecadb4520059cb00bba1858eedfaf808 | bmihovski/PythonFundamentials | /closest_two_points.py | 858 | 4.09375 | 4 | """
Write a program to read n points and find the closest two of them.
Input
The input holds the number of points n and n lines, each holding a point {X and Y coordinate}.
Output
The output holds the shortest distance and the closest two points.
If several pairs of points are equally close, print the first of t... |
2af3d781de561ba03575c81b764a62abab97f68a | pmeystre/caesarCipher | /caesar.py | 3,887 | 3.59375 | 4 | import string
import time
from operator import itemgetter
import nltk
from nltk.corpus import words
from rich.console import Console
from rich.table import Table
def main():
start_time = time.time()
ciphered_text = input(str('Enter text to decipher: '))
try_iterations(message=ciphered_text)
end_time =... |
62ca719e465378fdb3bef0c26327d20247f08749 | allenliuzihao/PyAlgorithm | /PyAlgorithm/Greedy_Algorithm/bst_huffman_code.py | 3,229 | 3.5625 | 4 | '''
code for binary tree
'''
import sys
from heap import Heap
sys.path.append("../Data_Structure")
from bst_node import TreeNode
class HuffmanBinaryTree(object):
"""docstring for BinaryTree"""
def __init__(self, words_stats):
heap = Heap(True)
for word in words_stats:
node = TreeNode(word)
node.setValue... |
5d940a87eee0123f786090dd4ba3dcf71b55a4ba | allenliuzihao/PyAlgorithm | /PyAlgorithm/Greedy_Algorithm/graph.py | 8,366 | 3.65625 | 4 | '''
Graph representation for graph problems. Node value is assumed to be unique
'''
class Edge():
def __init__(self):
self.endnodes = []
self.weight = 0
self.name = ""
self.reverse = False
self.visited = False
def setSelected(self, visited):
self.visited = visi... |
ce3e8ef6ca5a7fe753a88d14cfb2af9fb5d391b2 | charlieeWang/fileMover | /move.py | 1,296 | 3.546875 | 4 | import os
from shutil import copy
from sys import argv
def move_files(dir, dst):
"""
To iterate over every files (in here is .jpg / .mp4 )
in a given directory (dir), and copy them to another folder (dst).
for example, tree structure like this:
Album
├─2018
│ ├─07
│ │ ├─07
│ │... |
f85af68df85c10b74f31e2013ee06b9fac65fbea | jasoncox576/MountainVillage | /mountain_village.py | 24,245 | 4.09375 | 4 | # mountain village program
""" Jason Cox- February 2017
My First big python project
An idea for a mountain-climber game.
It uses the livewires package, a watered-down version of pygame.
It can be installed with all the necessary packages here: https://github.com/livewires/python
If I were to refactor it now, I would... |
535d722df010d1ef938e2673cea3a0a21685a7fe | ndcornelius/python-EGEC | /encryption/GroupOperations.py | 2,755 | 3.78125 | 4 | # Group operations for a group on Elliptic Curves for use in implementation of El-Gamal cryptosystem.
from encryption.ModularMath import modular_inverse, modular_sqrt
a = 0
b = 1
p = 5
def set_curve(c, d, e):
if (4*(c**3) + 27*(d**2)) % e == 0:
print("Invalid coefficients. Elliptic curve does not form... |
b8a296a7ded6c66b52fe7c3ce657ee30c37c2688 | wuhan027/Tensorflow- | /algo/solution_152.py | 508 | 3.5 | 4 | class Solution(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
tmax = nums[0]
tmin = nums[0]
result = nums[0]
for n in nums[1:]:
ttmax, ttmin = tmax, tmin
tmax = max(n, n*ttmax, n*ttmin)
... |
56488de42865378b715dab1f97e74643f27a47dc | heldaolima/MiniCursoIC | /Repeticao-LISTA-2/2 - 002.py | 270 | 3.859375 | 4 | n = int(input('Informe um número inteiro: '))
perf = 0
for i in range(1, n+1):
if n % i == 0:
perf = perf + i
perf1 = perf - n
print('----------')
if perf1 == n:
print(f'O número {n} é PERFEITO.')
else:
print(f'O número {n} NÃO é perfeito.')
|
521cdba3672899b759bcbbf8d63cc1bc9097e6df | heldaolima/MiniCursoIC | /Lista - Condicional/1).py | 689 | 4.03125 | 4 | """Faça um programa que peça o capital inicial de uma aplicação financeira e o montante final.
Em seguida, calcule os juros sobre esse investimento. Se os juros forem menor ou igual à 10% retorne
(“ Não faça o investimento “), se forem maior do que 10% retorne (“Faça o investimento”)."""
capital = float(input('Qual o ... |
d92a918b6cfb2f15386e235fdd3f2f2f3c7d8291 | heldaolima/MiniCursoIC | /PROVA/1) A.py | 584 | 4.15625 | 4 | print('''Questão1- Fazer um programa que peça uma quantidade de números e em seguida separar os números
que forem pares e colocar em um vetor e os que forem impares e colocar em outro vetor. Ao final printar
os vetores.''')
print('----------------')
pares = []
ímpares = []
quant = int(input('Quantos números deseja ins... |
900676fa8bfdab475627b50c8df6806ad6bb324c | Agent-Hellboy/cryptography | /CLASSIC_CIPHERS/OTP(one_time_pad)1.py | 1,678 | 3.671875 | 4 | from random import randint
def convert_to_bits(n,pad):
result=[]
while(n>0):
if(n%2==0):
result=[0]+result
if(n%2!=0):
result=[1]+result
n=n//2
while(len(result)<pad):
result=[0]+result
return result
#print(convert_to_bits(10,6))
def strings_to_bits(s,pad):
result=[]
for c in s:
result=convert... |
2b02bd704d2ba7e4e0ebc05f6e037924b9e4e0fa | azamatkb/Hello_python | /problem5+.py | 269 | 3.8125 | 4 | a = - 21 / 10
print (a)
print (-1 * 21 / 10 == - 21 / 10)
#Отрицательное число после деления всегда остается отрицательным,
#а при делении на 10 всегда отнимается один знак.
|
bfddd2af9f51e15b2245208cfda079c5619f7682 | izabelaguiar/class | /hw0/npdes_AS00.py | 6,455 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 10 10:46:07 2017
@author: izabelaguiar
nPDES AS00
Homework 0, due 2017-09-13
Fork the class repository, clone, and create a directory hw0 inside the repository.
Add your source file(s) to that directory.
Write a function diffmat(x) that returns a... |
f4014501962d1f47ac65cb38a6394ace0e207283 | samikojo-tuni/2021_Python-ohjelmointi_3004 | /Exercises/Timer/timer.py | 2,677 | 3.671875 | 4 | # Kirjoita ajastin.
# Ajastin toimii siten, että käyttäjä syöttää ohjelmaan tunnit, minuutit ja sekunnit
# Tämän jälkeen ajastin lähtee laskemaan syötytystä ajasta alaspäin tulostaen uuden
# ajan sekunnin välein komentokehotteeseen.
# Ohjelman suoritus päättyy, kun ajastin käy loppuun.
# Käytä viime viikolla tekemäämm... |
f6de0a2a294738a45520c90ff097ce62cbd9f98b | samikojo-tuni/2021_Python-ohjelmointi_3004 | /Exercises/RockPaperScissors/rps.py | 1,153 | 3.71875 | 4 | from enums import Choice
from player import HumanPlayer, CPUPlayer
# 0 kuvaa tasapeliä, 1 kuvaa 1. pelaajan voittoa ja -1 kuvaa 2. pelaajan voittoa
WinningConditions = {
Choice.ROCK: {
Choice.ROCK: 0,
Choice.PAPER: -1,
Choice.SCISSORS: 1
},
Choice.PAPER: {
Choice.PAPER: 0,
Choice.ROCK: 1,
... |
74b7972809949345b92a1dd4a67b89b99af596e3 | samikojo-tuni/2021_Python-ohjelmointi_3004 | /Examples/list.py | 1,147 | 3.921875 | 4 | cars = ["Toyota", "Volvo", "Mazda", "Ford"] # Hakasulkeet kuvaa listaa
print(cars)
# append lisää alkion listan loppuun
cars.append("Jeep")
print(cars)
# insert lisää alkion tiettyyn listan indeksiin
cars.insert(1, "Fiat")
print(cars)
# Poistaa alkion tietystä indeksistä
cars.pop(2)
print(cars)
# Pop ilman paramet... |
e1ece254c1c9b5cbec48c4b4501a9554e1e6f497 | smottahedi/learning | /algorithm/binary_search.py | 614 | 4.09375 | 4 |
def binary_search(input_array, value):
low = 0
high = len(input_array) - 1
while (low <= high):
middle = int((high + low) / 2)
if input_array[middle] == value:
return middle
elif value < input_array[middle]:
high = middle - 1
elif value > input_array[... |
8bb67426b8bd6621e5f2551db8df5b1c8b1c644b | juan-ivan-NV/prework-data-ironhack | /1.-Python/5.-Temperature-Processor/temperature.py | 3,062 | 3.84375 | 4 | temperatures_C = [33, 66, 65, 0, 59, 60, 62, 64, 70, 76, 80, 81, 80, 83, 90, 79, 61, 53, 50, 49, 53, 48, 45, 39]
#1 Find the minimum temperature of the day and store it in a variable
min_temp = min(temperatures_C)
#2 Find the maximum temperature of the day and store it in a variable
max_temp = max(temperatures_C)
#3... |
8207106df07683bde838444c54e7c11d41b33d28 | zybeasy/Misc | /a.py | 855 | 3.984375 | 4 | def myzip(*args):
iters = map(iter, args)
while iters:
res = [next(i) for i in iters]
yield tuple(res)
print(list(myzip('12', '34')))
# 注意这段代码在python2和python3中不同的执行结果
# 在python2中这段代码输出[(‘1’, ‘3’), (‘2’, ‘4’)],其实bool(iters)一直为真,直到next(i)抛出了StopIteration
# 结束了while循环
# 在python3中 iters是一个单次可迭代对象,而不是python2中的... |
73326ee1545b416b438361f0910fb0eb170699c1 | AlexAK87/gb_lesson_1 | /Kurochkin_Alexey_dz_3.py | 593 | 3.71875 | 4 |
number = input('Введите число от 0 до 20 или введи / для проверки ')
if number == "/":
i = 0
while i != 21:
if i == 1:
print('{} процент'.format(i))
elif i >= 2 and i <= 4:
print('{} процента'.format(i))
else:
print('{} процентов'.format(i))
... |
c8f6519403c54b21e4493ef18a2970265f18e16c | raviteja1117/sumanth_ketharaju | /arguments_example.py | 453 | 3.859375 | 4 |
def sample_function(a, b, c, d, e):
sum_result=a+b+c+d+e
print(sum_result)
input_string = input("Enter two values to be added?")
#
input_values=input_string.split(" ")
print(input_values)
input_list = []
for i in range(len(input_values)):
input_list.append(int(input_values[i]))
print(input_list)
samp... |
5eb7af6dd3deb59ec1e461101d7bce6e12f2b673 | raviteja1117/sumanth_ketharaju | /while.py | 143 | 3.8125 | 4 | i = 1
while i <= 5:
print("hi", end=" ")
j = 1
while j <= 5:
print("raju", end=" ")
j += 1
i += 1
print()
|
a57db25ca2d98ef6fa2e2a1067d003063bc18e89 | raviteja1117/sumanth_ketharaju | /break.py | 173 | 3.640625 | 4 | av = 5
x = int(input("how many candles u want "))
i = 1
while i <= x:
if i > av:
print("out of stock")
break
print("candle")
i += 1
print("bye")
|
49edfb57facb1231b237cd90f018b4d5c679ebda | Donal-Flanagan/I2X | /diarmaidi2xpackage/compare_word_with_corpus.py | 6,850 | 3.578125 | 4 | import os
import pickle
from collections import Counter
from operator import itemgetter
from pprint import pprint as pp
from diarmaidi2xpackage import create_words_and_values, save_words_and_values
def get_all_txt_files_in_directory(directoryIn):
"""
Get all of the files in the directory which end in .txt
... |
7c6075e8292968970c42b7a5c31146523e3a5699 | JohnminerIv/spd_14_technical_problems | /string_to_int_atoi.py | 3,355 | 4.09375 | 4 | """
The function first discards as many whitespace characters as necessary until
the first non-whitespace character is found. Then, starting from this
character, takes an optional initial plus or minus sign followed by as many
numerical digits as possible, and interprets them as a numerical value.
"""
# You would like ... |
ff3077857faf2f0b429f2cdce4965eddecccb09c | dusty-g/PythonAssignments | /OOP/hospital.py | 1,354 | 3.671875 | 4 | # need to add function to check which beds are available and assign accordingly
import random
class Patient(object):
def __init__(self, name, allergies):
self.id = random.randint(1000, 9999)
self.name = name
self.allergies = allergies
self.bed = None
class Hospital(object):
def ... |
136269c71143b7930bdc351edecef56ef0024bef | dusty-g/PythonAssignments | /OOP/animal.py | 998 | 3.859375 | 4 | class Animal(object):
def __init__(self, name):
self.name = name
self.health = 100
def walk(self):
self.health -= 1
return self
def run(self):
self.health -= 5
return self
def displayHealth(self):
print self.name, self.health
# bird = Animal("dav... |
a0a379217f07bf7d392b2a6d08988e764bbccfc3 | dusty-g/PythonAssignments | /Fundamentals/names2.py | 822 | 3.609375 | 4 | users = {
'Students': [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
],
'Instructors': [
{'first_name' : 'Michael', 'last_name' : 'Choi'},
... |
a1a57231a26c53a81045786bfa05120fb0a2d09e | dutkiewicz/python-lodz-profilers | /main.py | 580 | 3.53125 | 4 | def is_duplicate(needle, haystack):
exist_counter = 0
for straw in haystack:
if straw.lower() == needle.lower():
exist_counter += 1
return exist_counter > 1
def read_data(filepath):
with open(filepath, "r") as f:
return f.read().splitlines()
def find_duplicates(source):
... |
76b9ff6c39faa2a26d7330c3dba24697cd3efd42 | wellisonxd/desafios-python | /desafio075.py | 587 | 3.953125 | 4 | numeros = (int(input('Digite quatro numeros: ')), int(input('Digite quatro numeros: ')),
int(input('Digite quatro numeros: ')), int(input('Digite quatro numeros: ')))
print(f'A) Quantas vezes aparece o valor 9? {numeros.count(9)}')
if numeros.count(3) == 0:
print(f'B) Em que posição foi digitado o primeiro val... |
6be4641e66a240a8af1b2d7f19f1fc00823b9692 | wellisonxd/desafios-python | /desafio076.py | 367 | 3.671875 | 4 | lista = ('Feijão', 7.90, 'Arroz', 4.60, 'Macarrão', 1.89, 'Grão de Bico', 6.99, 'Lentilha', 7.50,
'Cebola', 2.99, 'Carne', 51.25, 'Frango', 14.69, 'Farinha', 2.99)
print('-='*20)
print(f'{"LISTAGEM DE PREÇO":^40}')
print('-='*20)
c = 1
n = 0
for i in range(0, 9):
print(f'{lista[n]:.<30}R$ {lista[c]:... |
dd84f415f1d5877996ef0291bdd1394c72499c7d | wellisonxd/desafios-python | /desafio053.py | 388 | 4 | 4 | frase = str(input('Digite alguma frase: ')).strip().upper()
palavras = frase.split()
juntar = ''.join(palavras)
inverter = juntar[::-1]
#for letra in range(len(juntar) - 1, -1, -1):
# inverter += juntar[letra]
print('O inverso de {} é {}!'.format(juntar, inverter))
if inverter == juntar:
print('Temos... |
7794a4306e77793b105eb6c4404f98bb916594f1 | wellisonxd/desafios-python | /desafio085.py | 794 | 3.5 | 4 | geral = []
pares = []
impares = []
for c in range(0, 7):
num = int(input(f'Digite o {c+1}º número: '))
if num % 2 == 0:
if c == 0 or num >= pares[-1]:
pares.append(num)
else:
for pos, i in enumerate(pares):
if num < i:
pares.... |
8f88a0c11580b2e780b1b13aac26ec7e647a2ca6 | wellisonxd/desafios-python | /desafio101.py | 373 | 3.890625 | 4 | def voto(ano_nasc):
from datetime import date
ano_atual = date.today().year
resu = ano_atual - ano_nasc
if resu >= 18 and resu < 60:
return "VOTO OBRIGATORIO"
elif resu == 16 or resu == 17 or resu >= 60:
return "VOTO OPCIONAL"
else:
return "VOTO NEGADO"
prin... |
3417cf18e09feb381bdd2774fc95c21f70ef7601 | wellisonxd/desafios-python | /desafio057.py | 222 | 3.9375 | 4 | sexo = 'n'
while sexo != 'M' and sexo != 'F':
sexo = str(input('SEXO: ')).strip().upper()[0]
if sexo != 'M' and sexo != 'F':
print('Opção inválida, digite corretamente.')
print('Obrigado, bom dia!') |
2c6bc59de80f4f9adeb18a076076357accc0b730 | wellisonxd/desafios-python | /desafio068.py | 725 | 3.640625 | 4 | from random import randint
print('=-='*10)
print('JOGO DO PAR OU ÍMPAR')
print('=-='*10)
contP = 0
while True:
n = int(input('Digite um número para jogar: '))
game = str(input('Par ou Impar [P/I]? ')).strip().upper()[0]
comp = randint(1, 5)
print(f'Maquina escolheu {comp}.')
resul = (n + c... |
b5dc84ba591120d6540ed722a6b1f143d5202106 | wellisonxd/desafios-python | /desafio074.py | 776 | 3.984375 | 4 | from random import randint
'''sort = []
maior = menor = 0
for num in range(1, 6):
sorteio = randint(1, 9)
if num == 1:
menor = sorteio
elif sorteio < menor:
menor = sorteio
if sorteio > maior:
maior = sorteio
sort.append(sorteio)
tuple(sort)
print(f'Os valores ... |
70a297e443f96ff9a9819611ae5a7d4a8428b39e | wellisonxd/desafios-python | /desafio029.py | 344 | 3.8125 | 4 | velo = float(input('Qual foi a velocidade do carro que passou? '))
if velo > 80:
print('O veículo ultrapassou o limite de 80KM')
multa = (velo - 80) * 7.0
print('A multa dele será no valor de R${:.2f}'.format(multa))
else:
print('O veículo não ultrapassou o limite de velocidade!')
print('=-... |
f3bfa2b786bc26bac4efe8886dd0ab12382229ee | wellisonxd/desafios-python | /desafio043.py | 558 | 3.90625 | 4 | peso = float(input('Informa seu peso em KG = '))
altura = float(input('Informe sua altura = '))
imc = peso / (altura ** 2)
if imc < 18.5:
print('Você está ABAIXO DO PESO. IMC => {:.2f}'.format(imc))
elif imc <= 25.0:
print('Você está com o PESO IDEAL. IMC => {:.2f}'.format(imc))
elif imc <= 30.0:
... |
574d53dd1804d16337a6ef75dbd6d7f88a2fc338 | wellisonxd/desafios-python | /desafio051.py | 176 | 3.78125 | 4 | prim = int(input('Primeiro termo: '))
razao = int(input('Razão: '))
soma = prim
for c in range(1, 11):
print(soma, end=' -> ')
soma += razao
print('ACABOU!')
|
44b1bbdf01fae0f920594d7391690f5786eb4d0e | wellisonxd/desafios-python | /desafio078.py | 702 | 3.8125 | 4 | valores = []
maior = menor = 0
for c in range(0,5):
valores.append(int(input(f'Digite o {c+1}º valor: ')))
if c == 0:
maior = menor = valores[c]
else:
if valores[c] > maior:
maior = valores[c]
if valores[c] < menor:
menor = valores[c]
print('=-=' * ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.