blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
6a2ab5ec11b783932f538481581efb11d6bf9781 | rebekabato/DTU-archive | /Assignments_IntroductionToProgramming/Acidity.py | 575 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 24 14:34:35 2018
@author: bebi
"""
def pH2Category(pH):
category = ""
if 0.0 <= pH and pH < 3.0:
category = 'Strongly acidic'
elif pH >= 3.0 and pH < 6.0:
category = 'Weakly acidic'
elif pH >= 6.0 and pH <= 8.0:
category = ... |
f86ccc8b257823c5b9c2396d316cb7d70bec9464 | yym6472/leetcode_everyday | /2020-08-29/120 word ladder.py | 1,144 | 3.71875 | 4 | class Solution:
"""
@param: start: a string
@param: end: a string
@param: dict: a set of string
@return: An integer
"""
def ladderLength(self, start, end, dict):
dict.add(end)
from collections import deque
q = deque()
q.append(start)
visited = set([sta... |
0545432cc3ae63f8bb220c612c432a578835260f | fanury/fheacassign1 | /assignment1.py | 7,532 | 3.546875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
#从input中读取文件
def readtxt(filename):
f = open(filename) # 返回一个文件对象
#读取第一行
line = f.readline()
for i in line:
if i=='\n':
break
nodesnumber=int(i)
a=[]
line = f.readline()
while line:
l1=[]
... |
018b56fa81707e7a35999c8ccc1c41ae41ac5866 | loong520/Data-Structures-and-Algorithms-in-Python | /src/assignment04/solutions/02_find_right_first_large_num.py | 443 | 3.78125 | 4 | from random import shuffle
def findRightFirstLargeNum(l):
"""
:type l: List[int]
:rtype: List[int]
"""
res = [-1] * len(l)
stack = []
for i in range(len(l)):
while len(stack) > 0 and l[stack[-1]] < l[i]:
res[stack.pop()] = i
stack.append(i)
return res
... |
93baacf3ecf47c4851897fcfab3df9b4cf5f7bb0 | Harishkumar18/data_structures | /450_qn_ds_lb/reverse_array.py | 219 | 4.28125 | 4 | """
Reverse the array
"""
def reverse_array(arr):
n = len(arr)-1
reversed = []
while n >= 0:
reversed.append(arr[n])
n -= 1
return reversed
arr = [1,2,3,4,5]
print(reverse_array(arr)) |
323c3676021cf78e228235b116dd2e6c12794daf | spike688023/The-Python-Workbook-Solve-100-Exercises | /all_exercises/59.py | 889 | 4.3125 | 4 | #Print out three lines saying for instance item 1 has index 0, and so on.
a = [1, 2, 3]
for index, item in enumerate(a):
print("Item %s has index %s" % (item, index))
"""
我的寫法也是對的,但就 不像它的乾淨, 它有用 %s ,
傳入時,會自動轉 成str ,
而且還多用了個 enumerate(),
來看一下它的定義吧。
第二個值,代表它的起始值, 預設 從0開始,
The enumerate object yi... |
4763987db96294d8712c48bfa14e9e79b2aec4ee | Haleluyaa/python_workshop | /ObjInheritance.py | 417 | 4.03125 | 4 | class Shape :
def __init__ (self, width, height) :
self.width = width
self.height = height
class Rectangle (Shape) :
def area(self) :
return (self.width * self.height)
print('Area of Rectangle Calculation \nPlease enter values for calculate.')
w = int(input('Enter width : '))
h... |
ba4d8d98ad474c5c1d6a54fad81f9d3eead1f038 | remotephone/pythoncrashcourse | /ch01-05/04_03-tryityourself.py | 507 | 3.90625 | 4 | for num in range(1,21):
print(num)
print("One Million works, but commented it out for brevity. It looks like this:")
print("""
for miln in range(1,1000001):
print(miln)
""")
miln = list(range(1,1000001))
print(min(miln))
print(max(miln))
print(sum(miln))
odds = list(range(1,20,2))
print(odds)
threes = list(... |
0eeee0bbf256083adcb4efc6f4d3c8f1a61020d1 | varshajoshi36/practice | /leetcode/python/medium/UniquePathsDp.py | 601 | 4.125 | 4 | '''
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?'''
... |
3be393e7d5d453cbf2f2bfb617a91883af269a1b | SylvainDeker/Vehicle-ReIdentification | /main.py | 149 | 3.5625 | 4 | #!/usr/bin/python3
import sys
if True:
print ('Number of arguments:', len(sys.argv), 'arguments.')
print ('Argument List:', str(sys.argv))
|
65a9f3231427a7daaea182be3fe9b17941b65683 | alan1tavares/maratona-de-programacao | /beecrowd/iniciante/sequencia_logica.py | 143 | 3.765625 | 4 | int_n = int(input())
str_saida = ""
for c in range(1, int_n+1):
print( "%d %d %d" % (c, c**2, c**3))
print( "%d %d %d" % (c, c**2+1, c**3+1)) |
a77f24a4eaad50337d3a01bcb1536965c5232ddd | Metaller000/python-project-lvl1 | /brain_games/scripts/brain_calc.py | 925 | 3.640625 | 4 | #!/usr/bin/env python3
from brain_games import cli
from brain_games import bcore
def main():
print('Welcome to the Brain Games!')
name = cli.welcome_user()
print(f'Hello, {name}')
print('What is the result of the expression?')
cor_flag = True
for i in bcore.get_range():
num_first = bc... |
9058d6cb3c0f7ff4b0bea3f5213e88d4f99ff1be | kashyapa/interview-prep | /revise-daily/educative.io/medium-subsets/7_find_unique_trees.py | 885 | 3.859375 | 4 | class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def find_unique_trees(n):
if n <= 0:
return []
return findUnique_trees_recursive(1, n)
def findUnique_trees_recursive(start, end):
result = []
if start > end:
resul... |
73d16872d1f47c63817ded46848ef573985c50c5 | hhhhhhhhhh16564/pythonLearn | /02/04条件判断.py | 857 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
age = 20
if age >= 18:
print('your age is', age)
print('adult')
age = 3
if age >= 18:
print('your age is', age)
else:
print("小屁孩")
age = 3
if age >= 18:
print('adult')
elif age >= 6:
print('teenager')
else:
print('kid')
#elif是else if的缩写,完全可以... |
e2db31775c7399b76cfcb55f23a36c871b6c9b78 | suscaria/python3 | /codingbat/list2/sum13.py | 647 | 3.96875 | 4 | # Return the sum of the numbers in the array, returning 0 for an empty array.
# Except the number 13 is very unlucky, so it does not count and numbers
# that come immediately after a 13 also do not count.
#
#
# sum13([1, 2, 2, 1]) → 6
# sum13([1, 1]) → 2
# sum13([1, 2, 2, 1, 13]) → 6
def sum13(lst):
flag = False
... |
b0f1ef4bfb9ce186abc1faee0a737269b0f3428f | SpencerTruett/PasswordGenerator | /PasswordGenerator.py | 794 | 4.09375 | 4 | from random import seed
from random import randint
import random
import time
import string
print("Let's create a password!")
time.sleep(.5)
letters = input("How many letters should be in the password?: ")
numbers = input("How many numbers should be in the password?: ")
def random_alphaNumeric_string(lettersCount, ... |
8a675a181c1814cef5501888167f014741abf02b | ilyasrukh/Python-UAS | /enam.py | 1,099 | 4.03125 | 4 | def ff():
print ("Tugas Kalkulator")
#fungsi penjumlahan
def penjumlahan(a,b):
penjumlahan = a+b
return penjumlahan
#fungsi pengurangan
def pengurangan(a,b):
pengurangan = a-b
return pengurangan
#fungsi perkalian
def perkalian(a,b):
perkalian = a*b
return perkalian
#fungsi pemb... |
7b2a7733e2009e9e32bfc0e5fe113b7944bb0dd4 | athenKing/cryptoLab | /rsa/primes.py | 3,830 | 4.0625 | 4 | import random
def primes_sieve(limit):
"""
Finding array of prime numbers in range from 0 to limit
:param limit: max value of number to find prime
:return: list of prime numbers
"""
a = [True] * limit
a[0] = a[1] = False
for (i, is_num_prime) in enumerate(a):
if is_num_prime:
... |
62a781109d9669f12237e122705acdb9edaa6d9a | matus258/python | /exe_funcao.py | 71 | 3.640625 | 4 | #!/usr/bin/python3
def increment(x):
return x+1
print(increment(3))
|
7a1381bac0a0ba3c2f2736410d7ad051989bd6f3 | Baobab470/IlearnPY | /venv/C2LAB6.py | 326 | 3.5625 | 4 | structure = [{'Arizona': 'Phoenix', 'California': 'Sacramento', 'hawaii': 'Honolulu'}, 5000,6000,7000,['hat', 't-shirt', 'jeans']]
print(structure[1])
print(structure[0])
print(structure[4])
print(structure[0]['Arizona'])
print(structure[4][2])
del(structure[3])
print(structure)
structure.append("new value")
print(stru... |
441b370f0c959e5e3b0b79b21e2de24b463639d5 | omarXzain/data-structures-and-algorithms-401 | /data_structures_and_algorithms/challenges/array_binary_search/array_binary_search.py | 395 | 3.9375 | 4 | import math
def BinarySearch(arr, val):
start = 0
mid = None
end = len(arr) -1
while start <= end:
mid = math.floor( (start + end) / 2 )
if arr[mid] == val:
return mid
elif val < arr[mid]:
end = mid - 1
else:
start... |
03dbf3e08014fadba7feae454c05979c7569dfac | ertosns/aipy | /aipy/neural_network.py | 10,212 | 3.625 | 4 | import numpy as np
## Randomly initialize weight, and bias parameters of given layer dimensions.
#
# @param layer_dims python array (list) containing the dimensions of each layer in our network
# @return parameters python dictionary of parameters
# "W1", "b1", ..., "WL", "bL":
# Wl weight matrix of shape(layer... |
9b8cc842d0a28baa5a0dd770e3aff4e4261167c8 | mrfreer/57Exercises | /Program18.py | 322 | 4.0625 | 4 | #Temperature Converter
while True:
try:
temp = int(input("Enter the temperature:"))
except ValueError:
continue
else:
break
convert = input("To F or C")
if convert == 'F':
print(str(temp*(9/5) +32))
elif convert == 'C':
print(str((temp-32)*5/9))
else:
print("Invalid entry... |
75f02bf7df4361214ff5d43ce6f9445e0a97fcc4 | AHakeemSG/Data21Notes | /user_input_task.py | 1,436 | 4.15625 | 4 | # Task for user input to for individual to go to the cinema
age_prompt = True
name_prompt = True
while name_prompt is True:
name = input(f"What is your name? ".capitalize())
if name.isalpha():
name_prompt = False
else:
print("Please use alphabetic letters for your name!")
while age_promp... |
18c8424b450a3348e208bf1308486f3b4f187ba2 | BiljanaPavlovic/pajton-kurs | /begginer/7.cas/zadatak1.py | 311 | 3.96875 | 4 | ime=input("Unesite ime Petar:")
'''
while ime.lower()!="petar" and ime.lower()!="петар":
ime=input("Uneli ste pogresno ime, pokusajte ponovo:")
'''
while ime.upper() not in ["PETAR","ПЕТАР"]:
ime=input("Uneli ste pogresno ime, pokusajte ponovo:")
print("Bravo, uneli ste ispravno ime.")
|
ea6cb32ce39efc77c3cf31c8a24ee5c20d119348 | Rushi21-kesh/30DayOfPython | /Day-19/Day19_shahazada(ST).py | 645 | 3.78125 | 4 | if __name__ =='__main__':
n=int(input("Enter size of list:- "))
listint=[]
print("Enter element of listint")
dictionary={}
ans=-1
for i in range(n):
ele=int(input())
listint.append(ele)
dictionary[ele]=0
for i in listint:
dictionary[i]+=1
for... |
91b0db4365c91e70cd38f417e43a94bb821cf60b | vipulshah31120/PythonDataStructures | /Multiply.py | 432 | 4.40625 | 4 | # To print the table of a number and give the sum of all the values
def Multiply(n) :
n = int(input())
sum = 0
for i in range(1, 11) :
print(n, '*', i, '=', n*i)
sum += n*i
print('Sum: ', sum)
Multiply(int) # 'int' is used for the positional argument. If we haav... |
99545f90c377e8ff06fddf5a256d9c5bfd0c949e | zseen/hackerrank-challenges | /Python/Implementation/ElectronicsShop/ElectronicsShopRefactor.py | 762 | 4 | 4 | #!/bin/python3
import sys
def getMoneySpent(keyboards, drives, money):
maxSoFar = -1
for item in keyboards:
for i in range(0, len(drives)):
if maxSoFar < item + drives[i] <= money:
maxSoFar = item + drives[i]
return maxSoFar
def main():
sys.stdin = open('electr... |
39681fd4b879ca79c030db28d1bb2833b08be507 | chu-yik/python-playground | /find_pair.py | 985 | 3.84375 | 4 | def find_pair(A):
print("given array: {0}".format(A))
n = len(A)
# first find existing number of paris
current_pair = 0
for i in range(n - 1):
if (A[i] == A[i + 1]):
current_pair = current_pair + 1
# then compute which flip bring the most positive change
best_change = -1
... |
5e6228147e1362b846d27888f75244b775637ce0 | richardjharris/adventofcode-2019 | /q16.py | 6,188 | 3.578125 | 4 | import itertools
import math
import unittest
import util
def multiplier(col: int, row: int, cycle = [0,1,0,-1]) -> int:
"""
Returns multiplier (0, -1 or 1) for the value at column N
for row N. Both column and row are 0-indexed.
"""
return cycle[ ((col+1) // (row+1)) % 4 ]
def apply_fft(i: list, t... |
dbf91b01ab0ca63223aec6cf434cb4f503582de0 | lhsqjoe/mylearn-python | /python全栈课程笔记/高级语法/函数式编程/005.py | 680 | 3.796875 | 4 | # 装饰器
import time
def printTime(f):
def wrpper(*args, **kwargs):
print('Time: ', time.ctime())
return f(*args, **kwargs)
return wrpper
@printTime
def hello():
print('Hello world!')
hello()
print('---------------------------------------')
def hello2():
print('Hello world!222')
... |
3e652fcb5262918682e2204d5fd7f6c45461ec78 | FabioCostaR/aprendendoPYTHON | /Desafio77.py | 439 | 3.9375 | 4 | #Crie um programa que tenha uma tupla com várias palavras (sem acento).
#Depois disso, você deve mostrar, para cada palavra, quais são suas vogais.
palavras = ('encontro','indice', 'determinada', 'lista', 'passado', 'desejado','argumento')
for p in palavras:
print(f' \n Na palavra "\033[01;32m {p.upper()}\033[m... |
6f61df1592560fcf6d20c16a4c17b208371e3e10 | shobhit-nigam/onsemi_one | /day2/flow_control/3.py | 183 | 3.515625 | 4 | # relational operators
# flow control
# pseudo code, do not execute
if (age > 60 or age <8) and gender = "female" :
print("give them a seat")
else:
print("travel standing")
|
62f933314ee6508374b17506d5be40c1578ada79 | hansen487/CS-UY1114 | /Fall 2016/CS-UY 1114/HW/HW5/hc1941_hw5_q4b.py | 294 | 3.953125 | 4 | """
Name: Hansen Chen
Section: EXB3
netID: hc1941
Description: Program that calculates if a year is a leap year.
"""
def leap_year_calc(input_year):
if (input_year%400==0):
return True
elif (input_year%4==0 and input_year%100!=0):
return True
else:
return False
|
2c1cf3fe07901e34d1860de120928040018c3df7 | luk9400/python-kurs | /list4/task2.py | 848 | 3.8125 | 4 | #!/usr/bin/python
from random import randint, random
def generate_tree(height):
if height == 0:
return None
proper_tree = generate_tree(height - 1)
random_tree = generate_tree(randint(0, height - 1))
val = randint(0, 10)
if random() > 0.5:
return [str(val), proper_tree, random_... |
b86dc7eac5734dba523008a8cccc447bc05122dd | Trietptm-on-Coding-Algorithms/Cryptography-Python | /encoding.py | 216 | 3.8125 | 4 | temp1 = raw_input("Enter a number in hex: ")
num1 = int(temp1,16)
print "num1: ",num1
temp2 = raw_input("Enter another number in hex: ")
num2 = int(temp2,16)
print "num2: ",num2
xored = hex(num1 ^ num2)
print xored
|
9ffe7343bba2e36594604c338a5d39379f3be707 | mansiSarvaiya/Tower-Of-Hanoi | /Tower Of Hanoi/TOH.py | 329 | 3.875 | 4 | def TowerOfHanoi(n,src,dest,aux):
if n==1:
print("Move disk 1 from src ",src,"to dest",dest)
return
TowerOfHanoi(n-1,src,aux,dest)
print("Move disk",n,"from src",src,"to aux",dest)
TowerOfHanoi(n-1,aux,dest,src)
n=int(input("Enter no of disks"))
if(n>0):
TowerOfHanoi(n,'A','... |
7ec9004b9c8db4ba23ddab0d1bf78bf1e40f3c53 | ofiriluz/Python-Basics | /Advanced Topics/3. Lambdas and map reduce filter.py | 1,671 | 4.625 | 5 | # Lambdas are a small anonymous functions used to quickly perform an operation
# They take any amount of arguments, but only have one expression
# Lambdas syntax:
# lambda arguments: expression
# Lambdas are very useful for quickly evaluating boolean expressions for different scenarios
# Some scenarios are for mapping ... |
56da80d72628d0180f4c36ac0bdf9a480e1a191f | BlesslinJerishR/PyCrash | /__2__VariablesAndSimpleDataTypes__/strip.py | 343 | 3.75 | 4 | word = " python "
print(word)
print(f"length : {len(word)}")
#rstrip
word_rstrip = word.rstrip()
print(word_rstrip)
print(f"length : {len(word_rstrip)}")
#lstrip
word_lstrip = word.lstrip()
print(word_lstrip)
print(f"length : {len(word_lstrip)}")
#strip
word_strip = word.strip()
print(word_strip)
print(f"lengt... |
f264d395ccd16805fce335f027d269ac1f09f37c | mokshsharma089/GuideForPython | /Databases/Basics.py | 1,552 | 4.46875 | 4 | # MySQL Database
# To be able to experiment with the code examples in this tutorial, you should have MySQL installed on your computer.
# You can download a free MySQL database at https://www.mysql.com/downloads/.
#
# Install MySQL Driver
# Python needs a MySQL driver to access the MySQL database.
# In this tutorial we ... |
0c17ff2385de3d1add4fba69d9276abd54c7bd80 | caijiahao/machineLearning | /src/GA/best.py | 373 | 3.5 | 4 | # 0.0 coding:utf-8 0.0
# 找出最优解和最优解的基因编码
def best(pop,fit_value):
px = len(pop)
best_individual = []
best_fit =fit_value[0]
for i in range(1,px):
if(fit_value[i]>best_fit):
best_fit = fit_value[i]
best_individual = pop[i]
return [best_individual,best_fit]
if __name__... |
25b637173c7213c916af907290b459e550d00169 | wdonray/PythonFirstTime | /ClassesObjects.py | 2,773 | 4.34375 | 4 | "Classes Example"
class Animal(object):
'''Animal Object'''
__name = ""
__height = 0
__weight = 0
__sound = ""
def __init__(self, name, height, weight, sound):
self.__name = name
self.__height = height
self.__weight = weight
self.__sound = sound
def set_na... |
95d801a6b9ed2faba40644ae2ade8998f61457c9 | nptit/checkio | /numbers_factory.py | 819 | 3.84375 | 4 | #!/usr/bin/env python
# -*- coding:utf8 -*-
def checkio(data):
result = []
while data > 9:
is_found = False
for i in range(9, 1, -1):
if data % i == 0:
is_found = True
result.append(i)
data = data // i
break
if... |
9137a8bdec573783e71fdcb85bf4d1d6ea660996 | Grego22/Katas | /Python/8-kyu/Fix_The_Bugs/Solutions.py | 435 | 3.828125 | 4 | # my solutions
def my_first_kata(a,b):
if type(a) != int or type(b) != int:
return False
else:
return a % b ++ b % a
# other solutions
def my_first_kata(a,b):
#your code here
if type(a) == int and type(b) == int:
return a % b + b % a
else:
return False
def my_firs... |
7b75b7da37ed8114e624afeae90e68df488181ed | vivekindiya/recommendation-engine | /engine/RecommendationEngineUsingPearsonsR.py | 1,775 | 3.53125 | 4 | '''
Created on 30-Mar-2018
@author: Vivek Shah
'''
import pandas as pd
import numpy as np
def replace_id_with_title(movies, ratings):
"""We are replacing movieId in dataset ratings with the movie title from movies dataset."""
ratings['movieId'] = ratings['movieId'].map(movies.set_index('movieId')[... |
a988c13fb2392b9bd17bf90e91a619981ca1dd06 | parhamgh2020/kattis | /Veci.py | 311 | 3.78125 | 4 | num = input()
smallest = int(''.join(sorted(num)))
biggest = int(''.join(sorted(num, reverse=True)))
num = int(num)
if biggest == num:
print(0)
else:
while True:
if sorted(str(smallest)) == sorted(str(num)) and smallest > num:
print(smallest)
break
smallest += 1
|
537b5a1411e2a67bf9f02e408c7b9777025779b1 | tuipopenoe/DailyProgrammer | /Challenge154E_March_Madness_Brackets/Challenge154.py | 206 | 3.765625 | 4 | # Tui Popenoe
# Challenge 154 - March Madness Brackets
def removeBrackets(string):
brackets = ['[', ']', '{', '}', '(', ')']
for i in brackets:
string = string.replace(i, '')
print string
|
37656e64046b9f2ff82a2b3db52d87dffbca6c5a | irinaignatenok/Python | /week9/day3/classWork.py | 4,157 | 4.0625 | 4 | class Task():
def __init__(self, content, date):
self.content = content
self.date = date
def __str__(self):
return f"{self.content} {self.date}"
class TodoList():
def __init__(self, name):
# name is the name of the list
self.name = name
self.list_of_tasks... |
3166be9960ffbf1e7473f57e470f29a196b7cd6b | janssen-v/CSC1001-Basics | /Week 3 (After Lunar Break)/moreflowpractice.py | 449 | 3.953125 | 4 | workingHours = float(input('Input working hours: '))
hourlyRate = float(input('Input the hourly rate: '))
if workingHours > 40:
extraHours = workingHours - 40
standardHours = (workingHours - extraHours)
standardPay = standardHours * hourlyRate
overtimePay = extraHours * (hourlyRate * 1.5)
payAmount ... |
e4036c212f8f190e61a5668d99db22e7e72b4930 | LucasNoga/Workspace-Python | /DUT/DUT_TD/TD 1/ex 2.py | 407 | 3.859375 | 4 | n = int(input("Saisir le nombre de test que vous allez effectuer : "))
nb = int(input("entrez un nombre de reference : "))
i = 1
minimum = nb
maximum = nb
while i <= n:
nb = int(input("entrez un nombre de test : "))
if nb < minimum:
minimum = nb
if nb > maximum:
maximum = nb
i... |
b30d5551342116cda3049a8e0f0570b1509f2f69 | astromotivespacetech/odyneMDO | /rotation_matrix.py | 888 | 3.625 | 4 | import math
from earth import Earth
from vector3d import Vector3D
def rotation_angle(t):
return 2 * math.pi * (t / Earth.day)
def seconds(hours):
return hours * 3600
def rotate_Z(theta, vector):
x = vector.x
y = vector.y
z = vector.z
... |
10c67adf38b55c976ee5d449c92c0e45f997e3fe | WeiPromise/study | /day02_进制转换、数据类型详解、类型转换、运算符/04-转换成为整数.py | 455 | 3.734375 | 4 | #!/usr/bin/env python3.5
# encoding: utf-8
# Created by leiwei on 2020/8/13 10:28
# 使用int 内置类可以将数据转换成为整数
a = '31'
b = int(a)
print(a)
print(b)
# print(a+1) 报错
print(b + 1)
# 字符串不是合法的数字,报错
# x = 'hello'
# y = int(x)
# print(y)
# 十六进制需要加标识(数字0-9,字母:a/b/c/d/e/f)
x = '1a2f'
y = int(x, 16)
print(y)
# 八进制(数字0-7组成)
m =... |
85d401db320392cf01680db5a4dd64d3de24d54a | Byliguel/python1-exo7 | /code/piles/piles_code_3.py | 1,050 | 3.9375 | 4 | def tri_wagons(train):
""" Trie les wagons rouges/bleus d'un train
Entrée : un train avec des wagons bleus (nombre) et rouges (lettres)
Sortie : les wagons triés avec les bleus d'abord et les rouges ensuite
Action : utilise une pile """
global pile # Doit être globale pour pouvoir être modifi... |
d1b280de9d39bc14ff76d2e7f3139c12ed7cf1b7 | sergiogp90/clasesParticulares | /SGE/Tema1/Ejercicios/Boletin5UD1/ejercicio4.py | 3,397 | 3.671875 | 4 | # -*- coding: utf-8 -*-
class Direccion(object):
def __init__(self, calle, ciudad, cp, provincia):
self.__calle = calle
self.__ciudad = ciudad
self.__cp = cp
self.__provincia = provincia
def get_calle(self):
return self.__calle
def set_calle(self, calle):
se... |
776d634060990348df7ea6a4402c511d4e6bb668 | jonsmartins52/cev | /caixa_eletronico.py | 990 | 4.125 | 4 | '''Crie um programa que simule o funcionamento de um caixa eletrônico. No inicio,
pergunte ao usuário qual será o valor a ser sacado(num inteiro) e o programa vai
informar quantas cédulas de cada valor serão entregues.
considerando notas de 50, 20, 10 e 1. '''
notas50 = notas20 = notas10 = notas1 = totalnotas = v... |
db6513caa35640a8b1b9b8138bf3aa23e70e63d1 | sejongjeong/Algorithm-Baekjoon | /src/11729_하노이_탑_이동_순서.py | 297 | 3.96875 | 4 | def hanoi(N, departure, arrival, layover):
if N == 1:
print(departure, arrival)
else:
hanoi(N-1, departure, layover, arrival)
print(departure, arrival)
hanoi(N-1, layover, arrival, departure)
number = int(input())
print(2**number -1)
hanoi(number, 1, 3, 2) |
3da0925af01f17a09a27283e71f7f662b49e2b08 | qingDragon/Python_Time | /day04/json反序列化.py | 799 | 3.828125 | 4 | # import json
# f = open("test.txt","r")
#
# data = json.loads(f.read())
# print(data.get("name"))
#
# f.close()
import pickle
data = {'k1':123,'k2':'hello'}
#pickle.dumps 将数据通过特殊的形式转换为只有python认识的字符串
p_str = pickle.dumps(data)
print(p_str)
print(type(data))
#pickle.dump 将数据通过特殊的形式转换为只有python认识的字符串,并写入文件
with open("t... |
c7af94385f156d1b2868152bf62facd3f8bc1de4 | divyaguduru/Pyprobe | /userstory_3.py | 2,823 | 3.5 | 4 | CELLS = {
' _ | ||_|': 0,
' | |': 1,
' _ _||_ ': 2,
' _ _| _|': 3,
' |_| |': 4,
' _ |_ _|': 5,
' _ |_ |_|': 6,
' _ | |': 7,
' _ |_||_|': 8,
' _ |_| _|': 9
}
def derive_account_number(input):
cells = get_cells(input)
c... |
d3d79a98c2fddda65516338454e9c192621bd019 | 95chenjz/18-summer | /Binary search & sorted array/search for range.py | 1,240 | 3.59375 | 4 | def searchForRange(vector:list, target:int) -> list:
if vector.__len__() == 0:
return [-1,-1]
start = 0
end = vector.__len__() - 1
bound = [0,0]
# search for left bound
while start + 1 < end:
mid = start + (end - start) // 2
if vector[mid] == target:
end = m... |
c91fd791128f0cb003e2097adb5b74b27b99e3e0 | bedgerotto/curso-python | /aula 2/bloco3/26.py | 142 | 3.8125 | 4 | n1 = int(input('Digite um número: '))
n2 = int(input('Digite outro número: '))
soma = sum(range(n1+1, n2))
print('A soma é: ' + str(soma)) |
624fe062a43c179ca20247aa55dafd8ba6b1bcaa | 5kyliner/WebAcademyProject | /DZ03/3task_06.py | 403 | 3.984375 | 4 | """
Написать функцию, которая определяет количество разрядов введенного целого числа.
Пример:
>> func(40)
>> 2
>> func(404)
>> 3
"""
import time
a = str(input('Введите число\n>'))
print(len(a))
# a = input('Введите число\n>')
# c = 0
# for n in a:
# int(a) / 10 > 0
# c += 1
# print(c)
#
|
520e573f46899abbb475bce9ae47755a1517288c | EvanJamesMG/Leetcode | /python/String/022. Generate Parentheses.py | 1,605 | 3.75 | 4 | # coding=utf-8
'''
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
'''
import sys
class TreeNode(object):
def __init__(self, x):
self.val = x
self... |
a98365d6f12d0e0cf03aa132c95f9c9087370768 | manishas053/Python-Exercises | /TripForMeal/meal.py | 1,072 | 3.90625 | 4 | ##################################################################################################
## Winnie-the-Pooh does not like physical activity. He wants to have a meal n times, #
## traveling minimum possible distance. Help him to find this distance. #
## First line contain... |
3be1a359cffc1050286ccabcf385ee036171034b | barbatus/algo | /code_signal/min_diff.py | 896 | 4.0625 | 4 | # You are given two positive integer arrays nums1 and nums2, both of length n.
# The absolute sum difference of arrays nums1 and nums2 is defined as the sum of |nums1[i] - nums2[i]| for each 0 <= i < n (0-indexed).
# You can replace at most one element of nums1 with any other element in nums1 to minimize the absolute... |
a4625b003ca3bb143650279f5003548bc4521b22 | rahulbisht12/Coding-Problems | /Hackerblocks/Algorithms/Lower Upper.py3 | 119 | 3.9375 | 4 | c=input()
if(c.isupper()):
print("UPPERCASE")
elif(c.islower()):
print("lowercase")
else:
print("Invalid")
|
81558f17c72ebe89c803b7c21396d2b3cff6a229 | rubinshteyn89/Class_Spring | /Python/Lab_8/Class_Exs.py | 2,174 | 4.34375 | 4 | __author__ = 'ilya_rubinshteyn'
# Pseudocode
#
# display the game instructions
#
# determine who goes first
#
# create an empty tic-tac-toe board
#
# display the board
#
# while nobody's won and it's not a tie
#
# if it's the human's turn
#
# get the human's move
#
# update t... |
bae77ef1bcfd52b18a27da91775d48219d42aaeb | abandre/abandre.github.io | /so/labs/lab4/lock.py | 583 | 3.59375 | 4 | from threading import Thread
from threading import RLock
import time
import random
g = 0
lock = RLock()
def incrementa():
global g
lock.acquire()
tmp = g # le valor
tmp += 1 # incrementa
lock.acquire()
time.sleep(random.randrange(0, 2))
lock.release()
g = tmp # escreve
lock.release()
if __name_... |
3f0e80b450e07334c1da577999590a29e5010b04 | matheuszei/Python_DesafiosCursoemvideo | /0020_desafio.py | 459 | 3.859375 | 4 | #O mesmo professor do desafio anterior(19) quer sortear a ordem de apresentação
# de trabalhos dos alunos. Faça um programa que leia o nome dos quatro alunos
# e mostre a ordem sorteada.
from random import shuffle
n1 = input('Digite o 1° nome: ')
n2 = input('Digite o 2° nome: ')
n3 = input('Digite o 3° nome: ')... |
2fc65c008054fc4a840fb43409d6bbfe3f3350ab | krislinnn/password | /password.py | 421 | 3.953125 | 4 | #密碼重試程式
#password = 'a123456'
#讓使用者重複輸入密碼
#最多輸入3次
#如果正確就印出“登入成功!”
#如果不正確就印出“密碼錯誤!還有__次機會
password = 'a123456'
i = 3 #剩餘次數
while i > 0:
pwd = input('請輸入密碼: ')
if pwd == 'password':
print('登入成功!')
else:
i = i - 1
print('密碼錯誤!還有', i, '次機會')
|
68d36e41896e1196eb56cf79013cdd06cdd4bc57 | rob-by-w/Invent-with-Python | /Chapter_1_Bagels/Bagels.py | 1,921 | 3.90625 | 4 | from random import randint
def input_guess(count):
print(f'Guess #{count}:')
guess = input('> ')
while len(guess) != 3 or not guess.isdigit():
print('Invalid input. Please input 3-digit number.')
guess = input('> ')
return guess
def check_guess(guess):
output = ''
for idx, d... |
caea3832713172f1c6a06076dbf22922b9e27175 | abdibogor/The-Bad-Tutorial | /05_Python/16_Nested IF-ELSE Statement/if_Nested.py | 500 | 4.09375 | 4 | char=input()
if ord(char)>=65 and ord(char)<=90:
print("You entered an upper case alphabet.")
if char in ['A','E','I','O','U']:
print("You entered a vowel.")
else:
print("You entered a consonnant.")
elif ord(char)>=97 and ord(char)<=122:
print("You entered an lower case alphabet.")
... |
c9b3777822eeedf5e8df419b5e00915a0a37fc74 | igorkoury/cev-phyton-exercicios-parte-1 | /Aula08 - Utilizando módulos/ex019 - Sorteando um item na lista.py | 427 | 3.84375 | 4 | # Um professor quer sortear um dos seus 4 alunos para apagar o quadro. Faça um programa que ajude ele, lendo o nome deles e escrevendo o nome do escolhido de forma aleatória
import random
a1 = str(input("Aluno 1: "))
a2 = str(input("Aluno 2: "))
a3 = str(input("Aluno 3: "))
a4 = str(input("Aluno 4: "))
lista = ... |
4aa0196c22ce2dff0783c88a041df12c9373b0f6 | ningyanke/book_p3 | /GUI/tkinter/code/鼠标点击事件.py | 931 | 3.953125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: ningyanke
# @Date: 2018-01-08 22:21:48
# @Last Modified by: ningyanke
# @Last Modified time: 2018-01-08 22:22:19
"""
鼠标点击事件
记录下的是事件在画布上的坐标值
: event.x ,event.y
"""
from tkinter import *
root = Tk()
def _printCoords(event):
print(event.x, event.y)
# 鼠标... |
ad124f86d70cc2b82e7b6e81dbf52525d991b52f | EtoDemerzel0427/Quarto | /warm-up/Loss.py | 2,481 | 3.515625 | 4 | """
In this simple version, I assume loss to be the same as an activation function,
from which we only need their values and grads.
"""
import numpy as np
from typing import Tuple
class Loss:
def __init__(self):
self.cache = None
def forward(self, inputs: np.ndarray, target: np.ndarray)... |
85beebb859955738b0f14f9d8db3c7bbfec6effb | arunkumardurgadevi/add | /odd.py | 86 | 3.8125 | 4 | a=int(input())
b=int(input())
for num in range(a+1,b):
if(num%2!=0):
print(num)
|
37269727b8d865d6f439056543b17435a8a7cb15 | Necron9x11/udemy_pythonWorkbook100Exercises | /ex-12/ex-12.py | 1,228 | 4.0625 | 4 | #!/usr/bin/env python3
#
# Python Workbook - 100 Exercises
# Exercise # NN
#
# Points Value: NN
#
# Author: Daniel Raphael
#
# ---------------------------------------------------------------------------------------------------------------------
#
# Question: Complete the script so that it produces the expected output.... |
4dc479c628e5ee326afa116a27a07b3579909b57 | AveryHuo/PeefyLeetCode | /src/Python/280.WiggleSort.py | 384 | 3.796875 | 4 |
class Solution:
def wiggleSort(self, nums):
for i in range(1, len(nums)):
if i % 2 == 1 and nums[i] < nums[i - 1] or \
i % 2 == 0 and nums[i] > nums[i - 1]:
nums[i], nums[i - 1] = nums[i - 1], nums[i]
return nums
if __name__ == "__main__":
solution ... |
b86accffed5165f5831216e3244ac1a1b3a9781b | sheyvwei/algorithm | /125IsPalindrome/IsPalindrome.py | 1,188 | 4 | 4 | '''
125 给定一个字符串,确定它是否是回文,只考虑字母数字字符并忽略大小写。 注意:出于此问题的目的,我们将空字符串定义为有效的回文
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Out... |
8fcf3af4a0dc4f9da2d9288294261b793af672e2 | Gabriel-ino/python_basics | /dictionary.py | 456 | 3.71875 | 4 | aluno = []
sit = {}
qtd_al = int(input('Digite a quantidade de alunos: '))
for al in range(0, qtd_al):
aluno[0] = str(input('Digite aqui o nome da aluno(a): '))
aluno[1] = float(input('Digite aqui a média do(a) aluno(a): '))
if aluno[1] >= 6.0:
aluno[2] = 'Aprovado!'
sit.append(aluno['res'])... |
5bf736aa8224408f3032fca540fe75c38994529e | netor27/codefights-solutions | /arcade/python/arcade-theCore/06_LabyrinthOfNestedLoops/050_CrosswordFormation.py | 1,698 | 3.625 | 4 | import itertools
def crosswordFormation(words):
'''
You're a crossword fanatic, and have finally decided to try and create your own.
However, you also love symmetry and good design, so you come up with a set of rules they should follow:
the crossword must contain exactly four words;
... |
16e32913cebea2b9c18a77b817a06f281c0e72b7 | Sana-mohd/functionsQuestions | /evenodd.py | 221 | 3.96875 | 4 | def shownumber(limit=int(input("enter your number: "))):
i=0
while i<=limit:
if i%2==0:
print( i,"even ")
else:
print(i,"odd")
i=i+1
print(shownumber())
|
fdd9b42837201910fa0d42d3e0dc7472ca3b8ffb | QuantumProductions/private-dice | /roll.py | 808 | 3.578125 | 4 | print "Obtain unloaded 6-sided dice."
print "It is your responsibility to ensure the evenness and fairness of these dice."
print "Enter your rolls (1-6). Do this 64 * 4 times to create a private key."
print "Each letter in the private key ranges from 0-F, determined by the odd or evenness in a sequence of 4 dice using ... |
e30ef9538661c9cafe41980cd503be3436ac267d | shankar7791/MI-10-DevOps | /Personel/Ruthwik/Python/Practice/23mar/prog2.py | 617 | 4.28125 | 4 | # Check whether the triangle is valid or not if angles are given using class
class triangle:
def __init__(self,a1,a2,a3):
self.a1 = a1
self.a2 = a2
self.a3 = a3
num_of_sides = 3
def check_angles(self):
my_tri = self.a1 + self.a2 + self.a3
if my_tri == 180:
... |
852b21e4609b75dfb7bf59a32720528e3d91f5fa | Songbz1999/pythonForFinance | /lesson2/Question 3.py | 767 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 11 16:11:46 2018
@author: Thinkpad
"""
#----------------------------------------#
#Question 3
#Level 2
#
#Question:
#Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters.
#Suppose the following input is supplied to... |
0d1aa5ae0dfc303bb60f3da29ef5f9c8d5d86fac | kirtymeena/DSA | /5.Searching/Q(count 1's).py | 458 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 5 09:34:16 2020
@author: Kirty
"""
arr=[1,1,1,1,0,0,0,0]
def count_1(arr,low,high):
if low<=high:
mid = low+(high-low)//2
if (arr[mid]==high or arr[mid+1]==0and (arr[mid]==1)):
return mid + 1
elif arr[mid]==1:
return ... |
aa03c3bd82774aca83c6f81d97930db620caaac4 | hypergirl/DailyCodingProblem | /Day1.py | 401 | 3.8125 | 4 | #Given a list of numbers and a number k,
#return whether any two numbers from list add up to k.
#For example, given [10, 15, 3, 7] and k of 17,
#return true since 10 + 7 is 17.
def twoSum(nums, target):
for i in range(len(nums)):
out=target-nums[i]
if(out in nums[i+1:]):
... |
040c00a946fc75cb895119c2003ba02e73b7e746 | hemanth-hs/google-capstone | /emails.py | 1,896 | 3.5 | 4 | #!/usr/bin/env python3
import smtplib # for sending mails
import mimetypes # to get the mimetypes of the files for attachement
import email.message # to create email in required format
import os.path
def generate_email(sender, recipient, subject, body, attachement_path):
"""Create an email with a... |
754f6d2162248daecb4a246b71d23294f44d71b8 | lazy928/gitlearning | /miniprojects/22Projects.py | 2,839 | 4.09375 | 4 | # -*- coding: utf-8 -*-
# 1 dice
# import random
# while int(input('Press 1 to roll the dice or 0 to exit:\n')): print(random.randint(1, 6))
# 2 Game of scissors paper rock
# import random
# choices = ["Rock", "Paper", "Scissors"]
# computer = random.choice(choices)
# player = False
# cpu_score = 0
# player_score = 0... |
b11d85a53c05107878db141f53e4f4b437d0e1fa | Zararthustra/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/9-print_last_digit.py | 182 | 4.21875 | 4 | #!/usr/bin/python3
def print_last_digit(number):
print('{}'.format(number % 10 if number > 0 else -number % 10), end="")
return (number % 10 if number > 0 else -number % 10)
|
32516d0f2bf72a52071e83f2b6992ea6fcff2332 | SupriyaMagare/test-demo | /If.py | 778 | 4.125 | 4 | # Example1
if ('Python' in ['Java','C#','Python']):
print("Python is present in the list")
if('C#' in ['Java','C#','Python']):
print("C# is present in the list")
if('Java' in ['Java','C#','Python']):
print("Java is present in the list")
# Example 2 Nested if
print("Example2")
num=-7
if (num!=0):... |
35950d78b21bc4dade75a77b1062593e2efdd28f | Dual-Exhaust/sleepingbarber | /BarberShop.py | 3,183 | 3.5625 | 4 | import random
import time
from threading import Thread, Event
import logging
# sets the logging level to INFO, default is WARNING
# also formats the logging to show time
logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s', level=logging.INFO, datefmt='%H:%M:%S')
class Barber:
# event ... |
2600822f285d718f7f37cb4d6d6426e2cd8f545e | Marcelo-Carlos/Python | /While/Varios-Valores.py | 191 | 3.859375 | 4 | n = c = s = 0
while n != 999:
n = int(input('Digite um numero inteiro: '))
if n != 999:
c += 1
s += n
print('Foram {} números digitados e a soma foi {}'.format(c, s)) |
a2013d0a2d22de975cc1c4b567153b3f88c09900 | Arytur/Python-exercise | /checkPrimalityFunction.py | 435 | 4.125 | 4 | # Ask the user for a number and determine whether the number is prime or not.
def check_primality(range_numb, numb):
range_numb = [y for y in range_numb if numb % y == 0]
if range_numb:
return range_numb
else:
return "Empty. No divisors."
number = int(input("Give me a number: "))
# empty ... |
9aa36723b4b1c8bd616894eee28f72582283d719 | yanjiuntw/polar_bp_decoder | /tools/write_verilog.py | 876 | 3.6875 | 4 | #! /bin/python3
def __input(name, n):
template = " input [SIZE - 1:0] " + name
for i in range(n):
print(template + str(i) + ",")
def __output(name, n):
template = " output [SIZE - 1:0] " + name
for i in range(n):
print(template + str(i) + ",")
def writeIO(n):
__input("in"... |
6fb90524285fb474782e42b9ce50678aa0fdd947 | Abdullah-786/MANUU | /1_Arithmetic_Operation.py | 274 | 3.921875 | 4 | # MANUU
x = int(input("Enter a numer "))
y = int(input("Enter another number"))
z1 = x+y
z2 = x-y
z3 = x/y
z4 = x*y
printf("sum of the number is",z1)
printf("subtract of the number is",z2)
printf("division of the number is",z3)
printf("multiplication of the number is",z4)
|
87a3d93f4c2e1bc60346466e1e10cb6a3f0c9d8b | vishalkumarmg1/Design-2 | /problem2.py | 1,419 | 3.828125 | 4 | # 705. Design HashSet
class MyHashSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.bucket =1000
self.bucketItem = 1000
self.hashset=[[False for i in range(self.bucketItem)] for i in range(self.bucket)]
def hash1(self, key):
... |
0ac26700bf03446d3d7e466e52d6ac031403ff5d | nicolejhui/python-basics | /integer-addition.py | 1,082 | 3.796875 | 4 | #take two integers and print the output
def addition(x, y):
sum = x + y
return sum
def subtraction(x, y):
difference = x - y
return difference
def multiply(x, y):
product = x * y
return product
def divide(x, y):
quotient = x/y
return quotient
# Pass in four numbers, add x, y, sub w, ... |
3d6f3014f9db56f08b30ca57c183c0573451969f | reduceme/python-start | /check_input.py | 438 | 4.125 | 4 | def get_user_input(start, end):
loop = True
while (loop):
try:
userInput = int(input('enter your choice'))
if userInput > end or userInput < start:
print("Please try again. Not in valid bounds.")
else:
loop = False
except Val... |
9e6149c8741a82906383ba1064f0412f4cd4cb85 | Faisal413/python-programming1 | /functions.py | 3,178 | 4.375 | 4 | from string import punctuation
from collections import Counter
def lowercase_text(text):
'''Returns a text string with all characters lower-cased.
Parameters
----------
text: str
Returns
-------
text_lowercased: str
Examples
--------
>>> lowercase_text('AbC')
... |
41bd595e53515d51208cb69850207ad9cd71858c | Shubham-tiwari123/Data-structures-using-Python | /swap.py | 1,543 | 3.953125 | 4 | class Nodes:
def __init__(self, data1):
self.data = data1
self.next = None
class Linklist:
def __init__(self):
self.start = None
def addnode(self, data):
new_node = Nodes(data)
if self.start is None:
self.start = new_node
else:
temp ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.