blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
a71a6603ee40fd07bcf73d2ccb802e29cb6ecb77 | julianascimentosantos/cursoemvideo-python3 | /Desafios/Desafio080.py | 462 | 3.984375 | 4 | valores = list()
for p in range(0, 5):
n = int(input('Digite um valor: '))
if p == 0 or n >= valores[-1]:
valores.append(n)
print(f'Valor adicionado ao final da lista.')
else:
p = 0
while p < len(valores):
if n <= valores[p]:
valores.insert(p, n)
... |
32902b17fb804bbebf87af86029ac1b43abf5931 | zosiadom96/pw_pwzn_z2019 | /lab_3/tasks/task_2.py | 1,313 | 4.125 | 4 |
def check_frequency(input):
"""
Perform counting based on input queries and return queries result.
Na wejściu otrzymujemy parę liczb całkowitych - operacja, wartość.
Możliwe operacje:
1, x: zlicz x
2, x: usuń jedno zliczenie x jeżeli występuje w zbiorze danych
3, x: wypisz liczbę zliczeń x ... |
2099fc18471834592e4c19c64622901573a4a835 | parveen99/infytqpy | /list_adjacent_pos_count.py | 336 | 3.765625 | 4 | #PF-Exer-18
def get_count(num_list):
count=0
for i in range(0,len(num_list)-1):
if(num_list[i]==num_list[i+1]):
count=count+1
# Write your logic here
return count
#provide different values in list and test your program
num_list=[1,1,5,100,-20,-20,6,0,0]
print(get_co... |
4b84a9df539fa6b5250a834f5292a626b92441f4 | overmesgit/hhtask | /square_solution.py | 4,232 | 3.90625 | 4 | """Solution for First Test Task of HeadHunter's School
Python3.4
author: Артем Безукладичный
mail: overmes@gmail.com
"""
import argparse
parser = argparse.ArgumentParser(description='Division in different number systems')
parser.add_argument('file', metavar='F', type=open, help='file')
args = parser.parse_args()
c... |
477537fecd9ace527877e344f202280ea705d384 | mardommah/from-linux | /python/project/konversi_suhu_fahrenheit_ke_celcius.py | 366 | 3.9375 | 4 | import math
#Program konversi suhu dari fahrenheit ke celcius
#Masukkan nilai celcius
F = int(input('Masukkan Suhu Dalam Fahrenheit: '))
if F < 32 or F > 212:
print('Masukkan suhu dengan benar')
else:
C = 5 * (F - 32) / 9
#fungsi round adalah untuk membulatkan angka beberapa di belakang koma
print(... |
1597646f29250908099ddeb9623abb0dd86f199f | TheWrL0ck/T-T-Lab | /LAB 5/prog7.py | 199 | 3.859375 | 4 | texts = ["php", "w3r", "Python", "abcd", "Java", "aaa"]
result = list(filter(lambda x: (x == "".join(reversed(x))), texts))
print("Palindromes present in the given list are:",end=" ")
print(result) |
87eadc4fc0b5a7a130a36c6f534bb7092ffa34b8 | microease/Python-Cookbook-Note | /Chapter_1/1.8.py | 450 | 4.125 | 4 | # 怎样在数据字典中执行一些计算操作(比如求最小值、最大值、排序等等)?
price = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}
min_price = min(zip(price.values(),price.keys()))
test = zip(price.values(),price.keys())
print(test)
print(min_price)
max_price = max(zip(price.values(),price.keys()))
print(max_... |
220cdf4cca2e86dfefe528f88eaa5b098c40d00b | sireesha98/laky | /laky.py | 483 | 4.25 | 4 | num1 = input()
# take input from the user
# num = int(input("Enter a number: "))
# prime numbers are greater than 1
if num1 > 1:
# check for factors
for i in range(2,num1):
if (num1 % i) == 0:
print(num1,"is not a prime number")
print(i,"times",num1//i,"is",num1)
break
... |
e5ac8bba4348249cf67b3be1d1fe1b2a16012131 | wko27/advent_2019 | /1.py | 377 | 3.671875 | 4 | import math
def calculate_fuel(value):
if value <= 0:
return 0
fuel = math.floor(value / 3) - 2
if fuel < 0:
return 0
return fuel + calculate_fuel(fuel)
sum_fuel = 0
with open("input1.txt") as f:
lines = f.readlines()
for line in lines:
mass = int(line.strip())
# breakpoint()
fuel = ca... |
1f78107b2913112540e32f9d093a6e8ebcf19b5e | Tokyo113/leetcode_python | /暴力递归到动态规划/code_01_Hanoi.py | 749 | 4.03125 | 4 | #coding:utf-8
'''
@Time: 2019/11/15 11:43
@author: Tokyo
@file: code_01_Hanoi.py
@desc:
'''
def Hanoi(n):
process(n, "左", "右", "中")
def process(i, start, end, other):
if i == 1:
print("move "+str(i)+' from '+start+' to '+end)
return
process(i-1, start, other, end)
print("move "+str(... |
f6d82529b14f8206291f5b7dc62acb5ebfd4a6eb | otmoru/lesson02 | /work05.py | 295 | 3.875 | 4 | my_list = [7, 5, 3, 3, 2]
i = 0
print('Наш список ', my_list)
while i < 10:
new = int(input('введите новый элемент для списка: '))
my_list.append(new)
print(my_list)
my_list.sort()
my_list.reverse()
print(my_list)
i += 1 |
b96f477b56ac5e0c3683cfc5c2a1634e3078a467 | barua-anik/integrify_assignments | /Python exercises/factorial.py | 201 | 4.34375 | 4 |
# Factorial operation using recursive function
def factorial(n):
if (n<=1):
return n
else:
return n * factorial(n-1)
print("The result is: ", factorial(int(input("Enter a number: "))))
|
707f2b86005dd29621ab5f87691c57e3fb5ff456 | naveencloud/python-basic | /dec182017/ps_stringfmt2.py | 986 | 4.375 | 4 | """demo for string formatting is for printing the rows and column {:fmt-str}"""
name, age, gender = 'sarah', 3, 'female' # Variable Parallel assignment
print("|{}|{}|{}|".format(name, age, gender)) # It will print output as directly
print("|{:>22}|{:>9}|{:>20}|".format(name, age, gender)) # It will have the Column ... |
9e64856d3426688bef12c689b7c497382b84869c | kafuuma/Fast-food-challenge2 | /app/users.py | 787 | 3.765625 | 4 |
from app.datastruct import DataStruct
store = DataStruct()
class Users:
"""This class handles creation and storing users in a Datastructure"""
def __init__(
self,full_name="", password="",
email="", contact="" ,user_role="",user_id =0,
):
self.full_name = full_... |
33e274fc73e9a00ab9fc7cff3e985c9e93d08bb0 | themohal/Python | /Quarter 1/Python/Part3/function1.py | 141 | 3.953125 | 4 | def add():
num1=int(input("Enter first number:"))
num2=int(input("Enter 2nd number:"))
print(f"{num1}+{num2}={num1+num2}")
add() |
f3fa7544a130494d8a6f4401e9de3a00c9dfdf58 | GLAU-TND/python-programming-assignment-2-Chetan-verma713 | /assignment_1.py | 213 | 3.640625 | 4 | ls = ['chair', 'height', 'racket', 'touch', 'tunic']
ls1 = []
p = ls[0][-1]
for j in ls:
for i in ls:
if p == i[0] and i not in ls1:
ls1.append(i)
p = i[-1]
print(ls1)
|
a315dda805ce9b3472a32e76c9e2cb98df66cbe1 | Vimlesh073/mynewrepository | /Python 24th Jan/ifEx.py | 969 | 3.984375 | 4 | n1 = 24
#check even no.
#if condition
if n1 % 2 == 0:
print('even no.')
#if else
if n1 % 2 == 0:
print(n1,' even no.')
else:
print(n1,' odd no.')
#if elif elif ......
#print day name
d = int(input('enter day no. '))
if d ==1:
print('monday')
elif d == 2:
print('tuesday')
elif d==3:
... |
5b6205b3e8d4316a20047f86979d508598d5d37f | abhishekrodriguez/Additional-files-python | /Dictionaries.py | 132 | 3.734375 | 4 | # Dictionaries
d1={"Hat": 35, "Toy": 50, "Vegies": 60}
print (d1 ["Hat"])
d1["Mat"]="55"
print(d1)
del (d1["Mat"])
print(d1) |
dc62a64a31c242866ce4bdf6ca011f37e0bf6401 | marcelxyz/kmeans-pyspark | /src/helpers.py | 680 | 4.0625 | 4 | import time
from datetime import datetime
def datetime_to_timestamp(datetime_value):
"""
Converts a datetime string of the format 2017-12-15T14:01:10.123 to a unix timestamp.
:param datetime_value: The datetime string to convert
:return: Integer timestamp
"""
return time.mktime(datetime.strpt... |
ee0633266ca2f71018db1d653d78f6a812a87798 | TayExp/pythonDemo | /05DataStructure/51二叉树的list实现.py | 519 | 3.65625 | 4 | def BinTree(data,left=None,right=None):
return [data,left,right]
def is_empty_BinTree(btree):
return btree is None
def root(btree):
return btree[0]
def left(btree):
return btree[1]
def right(btree):
return btree[2]
def set_root(btree,data):
btree[0] = data
def set_left(btree,left):
btr... |
acd8aeec3229d02b25bcfb753509728e0a7ba596 | Gokcekuler/Algoritma-Analizi | /maxsubsum_n_logn.py | 989 | 3.53125 | 4 | import time
start= time.time()
def max_of_two(a, b):
if (a > b):
return a
else:
return b
def max_of_three(a, b, c):
return max_of_two(a, max_of_two(b, c))
def my_f_3(a=[4, -3, 5, -2, -1, 2, 6, -2,4, -3, 5, -2, -1, 2, 6, -2]):
n = len(a)
if (n == 1 ) :
return a[0]
le... |
93dc3d7b314f6d6f423ed07db1e1151cd45706a8 | 6thfdwp/pygraph | /base.py | 7,974 | 3.875 | 4 | class Vertex:
"""
Vertex Class represents a vertex in graph
"""
#__slots__ = ['index', 'label', 'predecessor', 'status']
def __init__(self, label):
"""
Initialize vertex's attributes
index -- Self incremental integer storing its index in the whole graph
lable -- Stri... |
2fd11c95fc1328aabcb1d33f0060078db948b2d6 | YevgenyY/Python_Course2 | /week4/abstract_factory_pythonstyle.py | 2,553 | 3.515625 | 4 | class HeroFactory:
@classmethod
def create_hero(Class, name):
return Class.Hero(name)
@classmethod
def create_weapon(Class):
return Class.Weapon()
@classmethod
def create_spell(Class):
return Class.Spell()
class WarriorFactory(HeroFactory):
class Hero:
def... |
e8482fb2c62e14d6b07ac2d44c35a55ff7509b6d | Coconuthack/python-rice | /Interactive Python - P1/wk1-more-modules.py | 8,623 | 3.953125 | 4 | # Moduleeees
# - Modules are libraries of Python code that implement useful operations not included in basic Python.
# - Modules can be accessed via the import statement.
# - CodeSkulptor implements parts of the standard Python modules math and random.
#--------------------------------------
# Math Module
# The Math... |
abeec7de2b7217064bd1190e59f316a27a7b6b7d | heysushil/python-practice-set | /numpy/iteration.py | 1,856 | 4.0625 | 4 | # numpy
'''
npiter
EXAMPLE:
import numpy as np
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
# range(star,end,diff)
# np.nditer(start:end, ::number postion)
# if(2 <= 3) = IN nditer 1ST ARGUMENT 0 SHOWING STARING POINT AND 2 SHOWING N-1 SAME AS RANGE [0,2] = HERE 2 IS EXCU... |
0699321f82fc31d0c7e546f9664828c2488e0345 | gwy15/leetcode | /src/463.岛屿的周长.py | 1,953 | 3.59375 | 4 | #
# @lc app=leetcode.cn id=463 lang=python3
#
# [463] 岛屿的周长
#
from typing import List
from utils import *
# @lc code=start
class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
m = len(grid)
if m == 0:
return 0
n = len(grid[0])
# find the first land
... |
3c378233462324a64ec7dc929ed144d037a00d03 | Hui-Yao/program_yao | /python_note/01_学习总结/01_常见数据类型及其方法/03_元组方法.py | 679 | 3.90625 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Author = Hui_Yao
'''元组的增删改查:
创建:在创建一个元祖时,逗号比空格重要
删:只能直接删除整个元组,不能删除内部元素;元组内陆嵌套了可变对象另当别论
查:索引,分片
'''
print(type((123)),type((123,))) #未加逗号是int,加了逗号是tuple
print('元组方法'.center(50,'*'))
tiger = (123,'tiger','run')
xi1 = tiger.count(123) #1.count(value)——统计元组中val... |
e64e989e24706073deeb9ace266f98d83b72a91b | kristogj/alg_dat | /leetcode/self_dividing_numbers.py | 555 | 3.53125 | 4 | class Solution(object):
def selfDividingNumbers(self, left, right):
"""
:type left: int
:type right: int
:rtype: List[int]
"""
res = []
for x in range(left, right + 1):
if self.check(x):
res.append(x)
return res
def che... |
03c6eea9a943340e7e3b95a8b85e8f31b29e5484 | LoicGrobol/python-im | /exos/chifoumi.py | 1,750 | 3.953125 | 4 | # -*- coding: utf-8 -*-
# chifoumi tout nul fait en cours de Python
import random
def draw(coups):
"""
Coup aléatoire au chifoumi
pas d'arguments
"""
coup = coups[random.randint(0,2)]
return coup
def rules(player_1, player_2):
"""
implémentation naïve des règles du chifoumi
arg... |
367ca331e3b8ca2a6ea68491d62a4fda15ed1dc0 | kenzielizg/Cypher | /PythonApplication1.py | 23,834 | 4.125 | 4 | #Im too lazy to do full comments now
from math import floor
from math import ceil
#Called in sumHandleFloat, pascalString, pascalCypher, fibonacciString, fibonacciCypher, wordLengthCypher
def isAlphaNum(char, cyphNums=True):
"""
Checks if character is letter or number, returns bool
char: single characte... |
7154a2d9b46199e3a5dd7841cc94f163111a10a2 | Biddy79/eclipse_python | /Lists_Ranges_and_Tuples/Test_area/__init__.py | 728 | 4.4375 | 4 | sing_in_record = "D.K ", 21, ([])
#unpacking the tuple
company, location, time_in_out = sing_in_record
print(sing_in_record)
#company, location these values cannot be changed as the are tuples
#these values can be changed as they are list inside of tuple
time_in = float(input(print("Enter Time in: ")))
time_out ... |
8e5e4e74c8760257619ab7e1f87dcf3556e0dd6c | Klivanskaya/python_course | /lesson5/task4.py | 97 | 3.84375 | 4 | import string
st = list(input('Enter your string: '))
st.reverse()
print(st)
st.sort()
print(st)
|
45369aa4aa098f41693a810590eaa22652c549c8 | taillessscorpion/C4T-BO3 | /session7/part4/register3.py | 1,577 | 3.890625 | 4 | print('ĐĂNG KÍ TÀI KHOẢN')
uname = input('Tên đăng nhập: ')
print('Đã xác nhận thông tin cho tài khoản', uname)
while True:
password1 = input('Mật khẩu: ')
pwc = int(len(password1))
if pwc >= 8:
if password1.isalpha():
print('Mật khẩu phải có cả chữ và số. Mời nhập l... |
9705febbc96bd9cb7f424971e4fec101facca8f3 | AndrianovaVarvara/algorithms_and_data_structures | /TASK/Хирьянов 1 лекция черепаха/8_sq_spiral.py | 195 | 3.65625 | 4 | import turtle
x = 10
turtle.forward (x)
turtle.left (90)
for i in range (10):
turtle.forward (x)
turtle.left (90)
x += 10
turtle.forward (x)
turtle.left (90)
input()
|
062ce4be62326995c5af927418f58e864a107079 | CrisperDarkling/Richard_Teach_Python | /lists.py | 1,299 | 4.46875 | 4 | # Create a list
# literal
print("Literal list 0 to 4")
print([0, 1, 2, 3, 4])
# range function
# A range needs to be turned into a list to print it's contents
print("range 5 as list (0 to 4)")
print(list(range(5)))
# range function start, stop
print("range 3, 8 as list (3 to 7)")
print(list(range(3, 8)))
#range f... |
c361fc47bfb61b9c4b01ccfcff4c9d40b5245ea5 | cvlopes88/Sprint-Challenge--Intro-Python | /src/oop/oop1.py | 983 | 4.0625 | 4 | # Write classes for the following class hierarchy:
# [Vehicle]->[FlightVehicle]->[Starship]
# | |
# v v
# [GroundVehicle] [Airplane]
# | |
# v v
# [Car] [Motorcycle]
#
# Each class can simply "pass" for its body. The exercise is about setting up
# the hiera... |
fcda9b9fd249acc5f4eea5d91435dee691e3a7f8 | atwenzel/mutread | /source/plotting.py | 1,177 | 3.578125 | 4 | """Contains all the scripts for plotting data. Plotting package use is matplotlib, available at
http://matplotlib.org/. Every script should accept any number of data sets in implicitly paired lists, such that
data at index i in the xdata list should correspond to data at index i in the ydata list."""
#Global
import... |
e76a0105058be7d8aad6e00a7233f57fb67f31bf | daniel-reich/turbo-robot | /czLhTsGjScMTDtZxJ_8.py | 780 | 4.125 | 4 | """
In mathematics, primorial, denoted by “#”, is a function from natural numbers
to natural numbers similar to the factorial function, but rather than
successively multiplying positive integers, the function only multiplies
**prime numbers**.
Create a function that takes an integer `n` and returns its **primorial*... |
74fa381cecc57150b8aefc99b4c99ea490daa5b0 | GoncalezTI/Curso-de-Python-3-Mundo-01 | /PythonExercicios/ex016.py | 596 | 4.28125 | 4 | # 016 - Crie um programa que leia um número real qualquer pelo
# teclado e mostre na tela a sua porção inteira.
'''MODO 1
import math
num = float(input('Digite um valor: '))
print('O valor digitado foi {} e a sua porção inteira '
'é {}'.format(num, math.trunc(num)))
MODO 2
from math import trunc
num = float(inp... |
971d15ec70a6e89c917c3487703610bf70c50ed2 | samargunners/LPTHW | /Firstgame.py | 2,246 | 3.890625 | 4 | # which bike is for you.
def start():
print("You need to decide which bike is perfect for you.")
print("No problem, we will help you select")
choice = int(input("How old are you?: "))
if choice in range (18, 36):
excitingage()
elif choice in range (36, 51):
seniorrider()
elif ... |
2f07a30cd6ca7532942735f1bbeff0a8bcdaa32b | MrHamdulay/csc3-capstone | /examples/data/Assignment_6/fndjas001/question1.py | 552 | 4.1875 | 4 | """A program that takes a list of names and prints them right aligned
Jason Findlay
23/04/2014"""
Name=input("Enter strings (end with DONE):\n")
names=[]
Count=0
length=0
#fill list
while Name!="DONE":
if Name=="DONE":
break
else:
names.append(Name)
Name=input()
#find lon... |
efebe95c7d27e4b4c2e71e05b00e8580507ccb66 | rajat27jha/Neural-Nets | /First_model.py | 6,956 | 4.15625 | 4 | # tensor is just an array and flow means manipulations
# here w are going to use Mnist dataset beacuse its in the right format
# an imp work in ML to find a right datset taht suits a perticular model, here mnist data set suits prefectly
# training: 60000 sets, testing: 10000 sets
# mnist contain 28 by 28 hand written i... |
ad4b565fdd126f577b83806f0d0c7d772415811f | donmariolo/Introduction-to-Python | /tema5_3.py | 1,391 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed May 25 17:31:45 2016
@author: marioromero
"""
exponentes = range(1, 11)
exp_list = list(exponentes)
#Que tenemos en la lista? (en lenguaje natural).
print(exponentes)
print(exp_list)
#A~nadir a la lista de exponentes [18, 19].
print("---------------------------------------... |
b41040278dedcd9e81f0f249ae3c90b1e79e72f2 | usac201602491/Proyectos980 | /Parciales/Parcial1/Problema1.py | 583 | 3.609375 | 4 | N = 48 # Hasta donde se quiere encontrar el resultado de las sumas
def cuadrados(num):
respuesta = 0 # Resta de las sumas
suma1 = 0 # Suma de valores
suma2 = 0 # Suma de valores al cuadrado
for i in range(0,N+1):
suma1=suma1+i # Suma los valores de ... |
40f550e5540800e32b0c00fe953b59de23281b9f | akwls/PythonTest | /Part14. 리스트 더 알아보기/list_index.py | 218 | 3.65625 | 4 | def safe_index(my_list, value):
# 함수를 완성하세요
if value in my_list:
return my_list.index(value)
else:
return None
print(safe_index([1,2,3,4,5], 5))
print(safe_index([1,2,3], 5)) |
b3a13d461e7f10de1659e609733c812335719bed | vradja/leetcode | /Two Pointer/15. 3Sum.py | 1,427 | 3.65625 | 4 | class Solution:
# iterative method
def threeSum(self, arr):
triplets = set()
duplicate = dict()
arr.sort() # better sort here than sorting each tuple in two_sum
for index, value in enumerate(arr[:-2]):
if value not in duplicate:
self.two_sum(arr[inde... |
a1be667bc45b3560a13d581fd0b8ddebaa375636 | AndreisSirlene/Python-Exercises-Curso-em-Video-World-1-2-and-3 | /World1/challenge003.py | 118 | 3.875 | 4 | number1= int(input('First Number= '))
number2= int(input ('Second Number= '))
print('The sum is',number1+number2,'.')
|
2d0e762bba357cbd140e5c445c63880847dd2e66 | patidarjp87/python_core_basic_in_one_Repository | /65.cheaksubsettuple.py | 335 | 4.125 | 4 |
print("program to cheak whether a tuple is a subset of another tuple or not \n Enter super tuple")
t1=eval(input())
t2=eval(input("Enter child tuple\n"))
for x in t2:
for y in t1:
if x==y:
break
else:
print(t2,"is not a subset of",t1)
break
else:
print(t2,"is a subset of... |
5367ca049ba14dff592593bd6cc189b5c0d9a467 | albert118/Automated-Finances | /src/core/timeManips.py | 3,322 | 3.609375 | 4 | """
.. module:: timeManips
:platform: Unix, Windows
:synopsis: The time manipulation utility functions.
.. moduleauthor:: Albert Ferguson <albertferguson118@gmail.com>
"""
# third party libs
import numpy as np
import pandas as pd
# python core
import math
import os
import sys
import pickle
from datetime impo... |
ac2c53f9abf2ce6aab25b467a8a933d8613b1ffa | Sanjana-cell/Python-Programs | /Dictionary/RemoveKeyInDictionary.py | 272 | 3.859375 | 4 | sample={}
num=(int(input("Enter the size of dictionary")))
for i in range(1,num+1):
sample.update({i:i*i})
print("Before removing the key",sample)
key=(int(input("Enter the key to remove")))
if key in sample:
del sample[key]
print("After removing the key",sample)
|
d9d8485d0993fbae54b55449ea7cb77bb8398d26 | moce96/CPO | /src/immutable.py | 1,901 | 3.84375 | 4 | def size(n):
if n is None:
return 0
else:
return 1 + size(n.next)
def cons(head, tail):
"""add new element to head of the list"""
return Node(head, tail)
def remove(n, element):
assert n is not None, "element should be in list"
if n.value == element:
return n.next
e... |
39927ca56f12825e90de0499ee7749c962fb4948 | homezzm/leetcode | /LeetCode/中等/树/1261. 在受污染的二叉树中查找元素.py | 3,360 | 4.03125 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
from collections import deque
class FindElements(object):
"""
给出一个满足下述规则的二叉树:
root.val == 0
如果 treeNode.va... |
cdf047f0d67dcd900aba8ac7b4cff6fcbe4c2938 | JoaoAreias/Brilliant | /miller_rabin.py | 1,011 | 3.765625 | 4 | """
Miller-Rabin primality test
"""
from math import log
def gcd(x, y):
return y if not (x%y) else gcd(y, x%y)
def miller_rabin(n):
# Value checks
if not (type(n) is int):
raise ValueError("input must be an integer")
if n < 2:
return False
if n == 2:
return True
# Step 1: Determine k and m such that n-... |
d8402839449ea51f6e6391754525198cdd84e9ae | srthakor/ga-learner-dsmp-repo | /Project:-Student-Management-System/code.py | 990 | 3.75 | 4 | # --------------
# Code starts here
class_1=['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio']
class_2=['Hilary Mason','Carla Gentry','Corinna Cortes']
new_class=class_1+class_2
print(new_class)
new_class=class_1+class_2+['Peter Warden']
print(new_class)
del new_class[5]
print(new_class)
# Code ends ... |
41646f22cd1ebbdbabae811b14c97000e18a9187 | minseunghwang/algorithm | /programmers_re/해시/2.py | 559 | 3.5625 | 4 | def solution(phone_book):
l = len(phone_book)
phone_book.sort()
print(phone_book)
for i in range(l-1):
for j in range(i+1,l):
print(phone_book[i], phone_book[j])
if len(phone_book[i]) <= len(phone_book[j][:len(phone_book[i])]):
if phone_book[i] == phone_bo... |
a082da7d7d2f0d80bf7f33eeca73ca35e9939376 | pogross/bitesofpy | /47/password.py | 540 | 3.65625 | 4 | import string
import re
PUNCTUATION_CHARS = list(string.punctuation)
used_passwords = set("PassWord@1 PyBit$s9".split())
def validate_password(password):
pattern = re.compile(
# lowercase alphabetical, uppercase alphabetical, numeric, special character,
# 6-12 length
r"^(?=.*[a-z]{2,})(... |
4cb685007944e387bed456c138b662d41d095dbb | Anitha710/265441_Daily_Commits | /functions.py | 621 | 4.125 | 4 | def my_fun():
print("spam")
print("spam")
print("spam")
my_fun()
#use of return
def max(x, y):
if x>=y:
return x
else:
return y
print(max(9, 12))
z= max(17, 5)
print(z)
# Docstrings
def shout(word):
"""
print a word with an
exclamation mark following it.
"""
pri... |
5c84904c2dc75f8d0ffe2fe48cb78d4fb7973b80 | fedeh7/Shogi | /interface_shogi.py | 2,832 | 3.703125 | 4 | from shogi import Shogi, Rook, Lance, Pawn
class Interface():
def __init__(self):
self.game = Shogi()
self.turn_count = 0
# Inicia el loop del juego
def start_playing(self):
while self.game.is_playing:
self.turn_count += 1
self.input_origin_coordinates()
... |
04bb9b942978bffdc2619925f05a00fb9dc557af | FinOCE/CP1404 | /prac_05/word_occurences.py | 345 | 3.875 | 4 | words = {}
text_raw = input("Text: ")
text_array = text_raw.split(" ")
for word in text_array:
try:
words[word] += 1
except KeyError:
words[word] = 1
if '' in words:
words.pop('')
for word in sorted(words.keys()):
max_length = max([len(word) for word in words])
print(f"{word:{max_l... |
12f4b2ebb6f5eae34ed8ed83d6a4e72ad6fff13a | weitaishan/algorithm-basics | /Python/初级算法/数组_4_存在重复元素.py | 1,722 | 3.609375 | 4 | # *_*coding:utf-8 *_*
'''
存在重复元素
给你一个整数数组 nums 。如果任一值在数组中出现 至少两次 ,返回 true ;如果数组中每个元素互不相同,返回 false 。
示例 1:
输入:nums = [1,2,3,1]
输出:true
示例 2:
输入:nums = [1,2,3,4]
输出:false
示例3:
输入:nums = [1,1,1,3,3,4,3,2,4,2]
输出:true
提示:
1 <= nums.length <= 105
-109 <= nums[i] <= 109
'''
from typing import List
class Solution:
... |
d248d52cb70f5f8ab30393f559fd546db44ff5eb | junjaytan/python-data-structures | /CTCI/7_oo_solutions.py | 1,533 | 4.34375 | 4 | # 7.1
class Card(object):
""" abstract data type for card object """
def __init__(self, suit, value)
# probably want to ensure that values are allowed
if suit not in ["spade", "heart", "club", "diamond"]:
raise
self.suit = suit
self.value = value
class DeckOfCards(ob... |
9dd6520e6513fe2b558b08e47447e789747a8dbc | IanCBrown/practice_questions | /power.py | 252 | 4.0625 | 4 |
def exponent(a, b):
total = 1
for i in range(b):
total = multiply(total, a)
return total
def multiply(a, b):
total = 0
for i in range(b):
total += a
return total
print(multiply(5,3))
print(exponent(5, 3)) |
a066445887e9a5107b7e50511cefb7b18654fe0f | supvigi/python-first-project | /Tasks/2020_12_05/If/If24.py | 125 | 3.859375 | 4 | import math
x = int(input("Put in the X: "))
if x > 0:
print(2 * math.sin(x))
else:
print("Your result is", 6 - x)
|
d7652e6410dcda0bee7443d329fab052b03135a7 | baric6/ctf-python-ceaser-cipher | /decode.py | 377 | 3.546875 | 4 | #by baric
#this is a basic shift chipher the password is shifted +7
#shift -7 to get the password
counter = 0
vals = list('tfzbwlyzljylawhzzdvyk')
###################################################
asciiVals = []
for chars in vals:
asciiVals.append(ord(chars)-7)
#print(asciiVals)
newVal = []
for c in asciiVal... |
b66329b05b21d70dc4e6eaca9875d07c06e96e86 | Gummy27/Prog | /Assignment 1/Basic/question_5.py | 208 | 4.375 | 4 | d = float(input("What is the diameter?"))
import math
radius = d / 2
volume = (4/3)*math.pi*(radius**3)
volume_of_half_sphere = volume / 2
print("The volume of the half-sphere is", volume_of_half_sphere) |
237662b004176ce1d070a1dbdaeed745e9c788bd | diegopnh/AulaPy2 | /Aula 06/Ex003.py | 143 | 3.90625 | 4 | a = int(input('Digite um valor: '))
b = int(input('Digite outro valor: '))
s = a + b
print('A soma entre {} e {} é igual a {}'.format(a,b,s))
|
7b9dd19c72141cefcde272c8af48579568b449c0 | dlondonmedina/intro-to-programming-python-code | /4-1/car-all.py | 1,584 | 4.3125 | 4 | # define Car template
class Car:
def __init__(self, year, make, model, color, max_speed):
self.__year = year
self.__make = make
self.__model = year
self.__color = color
self.__max_speed = max_speed
self.__current_speed = 0
print("You now have a car with these ... |
b022e908ed5af3394d37eec7fb5b6cd453aef941 | AdamSierzan/Learn-to-code-in-Python-3-basics | /2. Python_data_types/9.1.2 Data_types_Boleans.py | 986 | 4.1875 | 4 | #let's put to variables
num1 = float(input("type the first number:"))
num2 = float(input("type the second number:"))
#now we can use the if statement, we do it like this
# if (num1 > num2)
#in the parentesis it is expecting the true or false valuable, in most programming languages we use curly braces,
# and everythin... |
f201e5f6d2c9903a6929a2c92d1ceaebf51f20ed | csyuanm/py-dashen | /learning/lf/chapter5/2-voting.py | 2,592 | 4.21875 | 4 | #coding=utf-8
#5.3 if语句
print('****************')
print('5.3 if语句')
#5.3.1 简单的if语句
#最简单的if语句只有一个测试和一个操作:
#if conditional_test:
#do something(若测试结果为True,则执行紧跟if语句后面的代码;结果为False,则不执行)
age = 19
if age >= 18:
print("You are old enough to vote!")
age = 19
if age >= 18:
print("You are old e... |
519d1ac902437a8d3788c1b14549115f13aed6b9 | ellemcfarlane/bioinformatics | /DistanceBetweenLeaves/distance_between_leaves.py | 3,658 | 4.09375 | 4 | # Elle McFarlane
from collections import deque
from collections import defaultdict
import heapq
def distance_between_leaves(n, weighted_tree):
"""
Computes the distance between leaves in a weighted tree.
:param n: number of leaves
:param weighted_tree: adjacency list with n leaves
:return: A n x n m... |
453c0a775ba63c1d6a1f70921db703cb2f731fbd | Jmueller87/learningpython | /mypolygon.py | 3,270 | 4.375 | 4 |
# This was a textbook project. The goal was to write functions using
# the turtle program that draw certain shapes and designs.
# I don't know the official solutions, but
# these various functions I wrote drew what they were intended to.
import math
import turtle
bob = turtle.Turtle()
print(bob)
... |
faa9fca2c29afc2bfd4b3717d98e52e3ef063f9e | klimek91/battleships | /new.py | 1,489 | 4.125 | 4 | from random import randint
board = []
for x in range(0, 5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print(" ".join(row))
print_board(board)
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
ship1_row = random... |
d6efd1bdad058c2b2efa936769624fce846ff34d | hsuanhauliu/leetcode-solutions | /medium/construct-binary-tree-from-inorder-and-postorder-traversal/solution.py | 1,121 | 4.09375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
""" Recursion reversed-pos-order traversal.
Tr... |
0f31bc774bd8ce63b835a71186f6b79d40069479 | Yukikazari/kyoupuro | /.提出一覧/AtCoder/除夜の鐘/arc019/a/main.py | 248 | 3.640625 | 4 | #!/usr/bin/env python3
#import
#import math
#import numpy as np
#= int(input())
S = list(input())
dic = {"O": 0, "D": 0, "I": 1, "Z": 2, "S": 5, "B": 8}
for i in range(len(S)):
if S[i] in dic:
S[i] = str(dic[S[i]])
print("".join(S)) |
cfe38dc15fd91be35f083f8e3577863cdced21a6 | zagrosbingol/Localfile-Invasion | /lfiencoding.py | 752 | 3.53125 | 4 | #/usr/bin/python3
import hashlib as hash
import base64
import myencodings
def welcome():
print("Please choose from the following options on what encoding you want?\n")
#List creation
mylist = ["base64", "urlencoding", "hex", "nullbyte", "All of the above"]
print("1.\t", mylis... |
8116814f9832ee37506f3206ec5a7cef0ff55823 | ravi4all/Python_WE_Jan_2 | /NativeDataTypes/03-Tuples.py | 481 | 3.6875 | 4 | Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> tup = (1,2,3,4,5,6,7,10)
>>> tup = (1,2,3,4,5,6,7,10,'hi','hello')
>>> tup[0]
1
>>> tup[-1]
'hello'
>>> tup[0:5]
(1, 2, 3, 4, 5)
>>> tup[0] = 'Hi'
Tra... |
3f4114c44cfd1cfeb61593934be1e5f91e06a80a | funny1dog/CTCI_python | /chapter_17/p17_4.py | 1,548 | 3.640625 | 4 | from typing import List
# Method: Count expected evens and odds, tehnically O(log_2(n^2))
# Time: O(n)
# Space: O(n)
def get_bit(a: int, bit_nr: int) -> int:
shifted_a = a >> (bit_nr)
return shifted_a & 0b1
def find_mssing(arr: List[int], n: int) -> int:
return find_missing_helper(arr, list(range(len(a... |
b64a4a01798b7b45da0a563d4ead5078261942aa | thehalovex/PythonCBT | /ifthenelse1.py | 268 | 4.0625 | 4 | name = input('Please tell me your name: ')
rawAge = input('Please tell me your age: ')
age = int(rawAge)
if age >= 20:
print(name, 'you are allowed in!')
print('What would you like to drink?')
else:
print('Unfortunately', name, 'you are not allowed in.')
|
be3322c3002ca4e06c7605d80d49a1da96286ca5 | kapilnavgurukul/python-logical | /list1.py | 152 | 3.71875 | 4 | list1 = [1, 342, 75, 23, 98]
list2 = [75, 23, 98, 12, 78, 10, 1]
new_list=[]
for i in list1:
if i in list2:
new_list.append(i)
print (new_list) |
03fe56a51dc37653742e46ceb59d32986e4ba988 | HermesBoots/holbertonschool-higher_level_programming | /0x0A-python-inheritance/4-inherits_from.py | 417 | 3.921875 | 4 | #!/usr/bin/python3
"""Module to check if object is from subclass of given type"""
def inherits_from(obj, a_class):
"""Determine whether obj is an instances of a subclass of a_class
Args:
obj: instance to check
a_class: class to check
Returns:
True if obj is instance of subclass o... |
a4126ce9f5468eaf9e2475cba1812c54aecca15d | zalecodez/Miniflow | /f.py | 554 | 3.96875 | 4 | """
Given the starting point of any `x` gradient descent
should be able to find the minimum value of x for the
cost function `f` defined below.
"""
import random
from gd import gradient_descent_update
def f(x):
return x**2 + 5
def df(x):
#Derivative of f with respect to x
return 2*x
x = random.randint(0... |
f03771b1c88d56f8df3c37b06beab03b85286e44 | vanuir/ESOF | /M5/Criar_Tabela/Criar_Tabela.py | 398 | 3.53125 | 4 | # 02_create_schema.py
import sqlite3
#conectando...
conn = sqlite3.connect("C:\M5\criando_uma_tabela\clients.db")
#definindo um cursor
cursor = conn.cursor()
#crindo a tabela (schema)
cursor.execute("""
CREATE TABLE clientes (
id,
nome,
idade,
cpf,
email,
fone,
cidade,
uf,
criado_em
);"... |
322fd88737758a18ae3c8ef02bb71792c2d90dab | jmmL/misc | /test2.py | 365 | 4.03125 | 4 | def main():
string_to_mangle = input("Enter a string:\n")
def piggy(pig_string):
if pig_string[0] == "a" or "e" or "i" or "o" or "u":
pig_string += "way"
return pig_string
else:
pig_string += "-" + pig_string[0] + "ay"
return pig_string[1:]
... |
0b992423b613c14b7886f9f3e98db46e5ecfddb9 | dwalley/ObsoleteRouteFinder | /dheaps.py | 8,682 | 3.609375 | 4 | # heaps module
import math
class dheaps():
def __init__(self,d,n,heap_type='max',less_than=None,greater_than=None):
###create an object of type dheap with length n, with each parent having up to d children###
self.heap_size = 0 # maximum index for which there is data
self.max_chi... |
2ac581b3551aa9e67ec836d823ebe17466fa3f1b | BibekKoirala/DynamicProgramming | /Fibonacci_Tabulation.py | 299 | 3.890625 | 4 | # Fibonacci series using Tabulation
# Time complexity Big O of this method is n
LookupTable = [None for i in range(6)]
def fib_tab(n):
LookupTable[0]=0
LookupTable[1]=1
for i in range(2,6):
LookupTable[i] = LookupTable[i-1] + LookupTable[i-2]
fib_tab(5)
print(LookupTable)
|
278b55cfd3a7e992853ad60b5419cba5e8e6266b | akalya23/gkj | /20.py | 91 | 3.59375 | 4 | ap=input()
ap=int(ap)
fact=1
for i in range(1,ap+1):
fact=fact*i
i=i+1
print(fact)
|
076c8188b5914ed062e437bc4acb11591b3ff04d | UX404/Leetcode-Exercises | /#374 Guess Number Higher or Lower.py | 710 | 4.1875 | 4 | '''
We are playing the Guess Game. The game is as follows:
I pick a number from 1 to n. You have to guess which number I picked.
Every time you guess wrong, I'll tell you whether the number is higher or lower.
You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0):
-1 : My number i... |
340269441ced53fda4fbc7a5ae61ce655a8f41e3 | hexinping/PythonCode | /practice/py_xml.py | 4,457 | 3.734375 | 4 | # -*- coding: UTF-8 -*-
'''
xml 解析
http://www.runoob.com/python/python-xml.html
python有三种方法解析XML,SAX,DOM,以及ElementTree
1.SAX (simple API for XML )
python 标准库包含SAX解析器,SAX用事件驱动模型,通过在解析XML的过程中触发一个个的事件并调用用户定义的回调函数来处理XML文件。
2.DOM(Document Object Model)
将XML数据在内存中解析成一个树,通过对树的操作来操作XM... |
727fc808aaf69cefbf4bc7a3fe7ab62ac264cde5 | DS-Veritas/CS-A111X_Car_Dealer_System | /Buyers.py | 1,134 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 22 11:38:18 2019
@author: Jeheon Kim
"""
from Cars import Car
class Buyer:
def __init__(self, name):
self.__bid_list = []
self.__name = name
# Buyer can make an offer to a single car they like the most
# Buyer's ... |
559d622908ae527112a98a2c22fd172fdaeba07c | dapazjunior/ifpi-ads-algoritmos2020 | /Fabio_01/Fabio01_Parte01/f1_p1_q15_area_triangulo.py | 240 | 3.828125 | 4 | # Entrada
base = float(input('Digite a medida da base do triângulo: '))
altura = float(input('Digite a medida da altura do triângulo: '))
# Processamento
area = (base * altura) / 2
# Saida
print(f'A área do triângulo é {area:.2f}.')
|
65afff46431ef801710e67889b69c172f0e742bf | fossabot/IdeaBag2-Solutions | /Numbers/Change Return Program/change_return_program.py | 2,797 | 4.21875 | 4 | #!/usr/bin/env python3
"""A program for calculating optimal change.
Title:
Change Return Program
Description:
Develop a program that has the user enter the cost of an item
and then the amount the user paid for the item.
Your program should figure out the change
and the number of quarters, dimes, nickels, pennies need... |
08da510a25d46094341e4f32f926358d598672e1 | legendronyang/python-exercise | /20160421_Convert.py | 2,077 | 3.765625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
6. ZigZag Conversion https://leetcode.com/problems/zigzag-conversion/
'''
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1:
return... |
b78199569f7449c4b35b7058bea56747cff4b079 | anku255/fyle-backend-coding-test | /bankService/db/db_helpers.py | 461 | 3.53125 | 4 | import psycopg2
import os
import psycopg2
from psycopg2.extras import NamedTupleCursor
def connectToDB():
try:
# Connect to an existing database
conn = psycopg2.connect("dbname={} user={}".format(
os.environ.get('DB_NAME'), os.environ.get('DB_USER')))
# Open a cursor to perform database operati... |
c1246ebbc0ab665c7316d1f7f4c1f66deee484c2 | axnessbatch/Srilatha | /large.py | 138 | 3.625 | 4 | a=[1,2,3,4,5]
b=[]
c=[]
for x in a:
if(x%2==0):
b.append(x)
else:
c.append(x)
print(b)
print(c)
print(b[-1])
print(c[-1]) |
0f986c9e5ab687a752298000176c992d8d7084e4 | kkzh2313/python | /test3-从头到尾打印链表 (2).py | 775 | 4.0625 | 4 | #输入一个链表,从尾到头打印链表每个节点的值。
class Listnode:
def __init__(self,x=None):
self.val=x
self.next=None
class Solution:
def printListFromTailToHead(self,listnode):
if listnode.val == None:
return None
l=[]
head=listnode
while head :
l.in... |
1054c23741242fb35d45143e10c1ceabb42d75f1 | charshal12/my-python-project | /conditions.py | 1,317 | 4.34375 | 4 | # We use conditions for below few reasons
# 1. Its should make sense(-negative output)
# 2.The program should not get crashed
# Conditionals
# Equals: a == b
# Not Equals: a != b
# Less Than : a < b
# Less Than or Equal To : a <= b
# Greater Than: a > b
# Greater Than or equal to : a >= b
# By validating user input val... |
0026327ddecf564fc36ff0cc51e3cf7bbaa71993 | curow/Problem-Solving | /leetcode/55/backtracking.py | 387 | 3.578125 | 4 | from functools import lru_cache
class Solution:
def canJump(self, nums: List[int]) -> bool:
final = len(nums) - 1
@lru_cache(maxsize=None)
def jump(current_pos):
if current_pos >= final:
return True
k = nums[current_pos]
return any([jump(cu... |
c85f92929e97131cc1d15b7ed996957e4d253aae | Emiya2098212383/Lesson02- | /03-string.py | 323 | 4.09375 | 4 | # 练习三
print("-----华丽分割线-----")
# 用户输入两串文字后合并输出
# 注:input() 返回一个字符串
text1 = input('输入第一串文本:')
text2 = input('输入第二串文本:')
# 求和
text3 = text1 + text2
# 显示计算结果
print ('新的字符串相加结果为:')
print (text3)
|
e9bde898d9eb5a2d21a5d3996ba342b09082466a | Angel-cuba/Python-UDEMY | /seccion-3/op-logicos.py | 599 | 4.1875 | 4 | # #Operador not
# print(not False)
# #operador And
# print(False and True)
# #operador or
# print(True or False)
# #Example
# c = "Python"
# print(len(c))
# if len(c) > 8:
# print('es mayor')
# else:
# print('es menor')
print("Sistemas de becas")
kilo = int(input("Cuanto kilometro para cami... |
b24da069d551b8a9b04fde4bd5893347dac7fae4 | Matheuspaixaocrisostenes/Python | /ex005.py | 146 | 3.984375 | 4 | n = int(input(' digite um numero: '))
a = n - 1
s = n + 1
print(' analisando o valor {} seu antecessor é {} e seu sucessor é {}'.format(n,a,s)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.