blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
c9f15d2bcda55de467e3673f73d80ea07524d1e0 | smirnoffmg/codeforces | /230A.py | 352 | 3.5 | 4 | # -*- coding: utf-8 -*-
s, n = map(int, raw_input().split())
dragons_and_points = []
for i in xrange(n):
dragons_and_points.append(tuple(map(int, raw_input().split())))
dragons_and_points.sort()
for power, treasure in dragons_and_points:
if s > power:
s += treasure
else:
print('NO')
... |
f2df5ca1e0f47be584f77de58f0f14b4427afe30 | smirnoffmg/codeforces | /465A.py | 263 | 3.5 | 4 | # -*- coding: utf-8 -*-
n = int(raw_input())
number = raw_input()
diff = 0
one = True
for i in xrange(n):
if number[i] == '1' and one:
diff += 1
one = True
if number[i] == '0' and one:
diff += 1
one = False
print(diff)
|
0016f064ede3097fe07bd3ea4c8282c58dd22448 | smirnoffmg/codeforces | /474A.py | 461 | 3.859375 | 4 | # -*- coding: utf-8 -*-
from string import maketrans
r_transtab = maketrans(
'qwertyuiop'
'asdfghjkl;'
'zxcvbnm,./',
'wertyuiopp'
'sdfghjkl;;'
'xcvbnm,.//'
)
l_transtab = maketrans(
'qwertyuiop'
'asdfghjkl;'
'zxcvbnm,./',
'qqwertyuio'
'aasdfghjkl'
'zzxcvbnm,.'
)
direct... |
9b3991a950dc93f7311925ac96143f6ef1c07864 | smirnoffmg/codeforces | /621A.py | 336 | 3.703125 | 4 | # -*- coding: utf-8 -*-
n = int(raw_input())
numbers = map(int, raw_input().split())
numbers.sort(reverse=True)
result = 0
odd = 0
for i in numbers:
if i % 2 == 0:
result += i
else:
if odd:
result += odd
result += i
odd = 0
else:
odd = i... |
dd75d06ea44d0a66eeb8922063c9804f6a92bcc9 | thomasathul/MusicPlayerDemo | /Daily_Assignments/Day-1 Assignment/problem_set_4.py | 1,171 | 3.609375 | 4 | def ipadd(string):
list1 = list(string.split("."))
decimal = 0
i = 3
for num in list1:
decimal += (int(num)*pow(256, i))
i -= 1
return decimal
def isogram(string):
set1 = set(string)
list1 = list(string)
return "It is an isogram" if len(set1) == len(list1) else "It is n... |
bc5afd281dca2da2360a3e724238c8974e836261 | thomasathul/MusicPlayerDemo | /3_Implementation/main.py | 1,577 | 4.0625 | 4 | """
Main function (Login and Signup
"""
from authenticate import SignUp, LogIn
import menu
def main():
"""
Main method contains login and signup features
:return:
"""
print("\n-----Welcome to MSS----- \n 1. Login \n 2. Signup")
tryexit = 1
choice = None
while tryexit:
try:
... |
650702a684e00a7cb8d471e1c6eba314247b8312 | SofiaShaposhnyk/ElementaryTasks | /tests/test_FibSequence.py | 1,265 | 3.765625 | 4 | import unittest
import FibSequence
class TestFibSequence(unittest.TestCase):
def test_get_fib_sequence_valid_value(self):
expected = "2, 3, 5, 8, 13, 21, 34, 55, 89"
result = FibSequence.get_fib_sequence(1, 100)
self.assertEqual(result, expected)
def test_validate_args_negative_value(... |
5c2f075d9533e74f1d842018ab786669bf9b1fb3 | SofiaShaposhnyk/ElementaryTasks | /NumSequence.py | 719 | 3.703125 | 4 | import sys
import math
def validate(args):
if len(args) == 2:
try:
limit = int(args[1])
except ValueError:
return "Limit should be integer."
else:
if limit > 0:
return limit
else:
return "Limit should be positi... |
84d608ba0fb808788426d769ed00a290f3f8407f | wako057/python | /src/exo00/part02.py | 717 | 3.53125 | 4 | # coding=utf-8
import random, math
import locale
locale.setlocale(locale.LC_ALL, '')
print("############## Part 2 ##############")
print("============== Exo 3 ==============")
max = 1000000
print("Tableau de 0 a ")
print("{0:n}".format(max).rjust(18))
l = list(range(0, max))
for k in range(0, 10):
x = random.ra... |
e4a9b638113ed3256094c0704997133349cadc9a | danigunawan/vgg_frontend | /siteroot/controllers/retengine/utils/timing.py | 503 | 3.515625 | 4 | #!/usr/bin/env python
import time
class TimerBlock:
"""
Class for timing groups of statements.
Used to time blocks of statements contained within a 'with' block
e.g. with TimerBlock() as t: <statements>
Upon exit from the block, the time taken is stored in t.interval
"""
... |
f21bd1ca010757daee9cbd8e412c4dea216e8c35 | artpods56/Matura-Informatyka-Python | /2019 Maj - Rozszerzenie/main.py | 2,133 | 3.546875 | 4 | """"
plik = open("przyklad.txt","r")
def czy_potega3(liczba):
x = 0
i = 0
while x <= liczba:
x = pow(3,i)
# print(f"{x} and {liczba}")
if x == liczba:
return True
else:
i += 1
return False
for liczba in plik:
liczba = int(liczb... |
623d3b30ad71234981f371de03393dfc239fc574 | SamanHashemi/Blue_v1.0 | /Actions/Time.py | 797 | 3.703125 | 4 | import datetime
import random
class Time:
def __init__(self):
# Trigger words from time
self.trigger_words = ["time"]
self.priority = 1
def time(self) -> str:
now = datetime
hour = now.hour
minute = now.minute
responses = ["Oh, right now it's", "It's", ... |
34fb9ad3ecabb18dd4aad355e5fd35e841968157 | rnb1984/msc_python | /Algorithms and Datastructures/Prim.py | 2,516 | 3.953125 | 4 | """
Prim
Prim's algorithm for minimum spanning trees.
Uses Adjcent Matrix.
"""
import csv
file_in = 'stdin'
####################################################################################
# Prim Algorithm
####################################################################################
def prim(gr... |
14905df9290c6e1a9017c3747997db20348b6487 | mpigrobot/python | /P11/P11-9.py | 258 | 3.96875 | 4 | class Person(object):
address='Earth'
def __init__(self,name):
self.name=name
print Person.address
p1=Person('Bob')
p2=Person('Alice')
print p1.address
print p2.address
Person.address='China'
print p1.address
print p2.address |
6cb17801eff358c27cf2e1a6dd6d44ed6bd6e0e8 | mpigrobot/python | /P13/13-19.py | 342 | 3.828125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
class Fib(object):
def __init__(self, num):
a, b, L = 0, 1, []
for n in range(num):
L.append(a)
a, b = b, a + b
self.numbers = L
def __str__(self):
return str(self.numbers)
__repr__ = __str__
... |
01cae8ba3abea26904f3b6327d1ac26d9f1f50bf | mpigrobot/python | /P10/10-6.py | 373 | 3.734375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# 匿名函数有个限制,就是只能有一个表达式,不写return,返回值就是该表达式的结果。
print filter(lambda s: s and len(s.strip()) > 0, ['test', None, '', 'str', ' ', 'END'])
def is_not_empty(s):
return s and len(s.strip()) > 0
print filter(is_not_empty, ['test', None, '', 'str', ' ', 'END']) |
b0e4be581e2e383be0e897cdef7171aa5d112108 | mpigrobot/python | /P13/13-12.py | 536 | 3.5625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
class Student(object):
# def get_score(self):
# return self._score
def set_score(self, value):
if not isinstance(value, int):
raise ValueError('score must be an integer!')
if value < 0 or value > 100:
raise ValueE... |
353e702379ebc8a6b91a62470dee0c0b4ead68c8 | mpigrobot/python | /P13/13-3.py | 778 | 3.953125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def __str__(self):
return '(%s: %s)' % (self.name, self.score)
__repr__ = __str__
def __cmp__(self, s):
if self.name < s.name:... |
49aff59b84406daf53b2c976a2ab435d18a64299 | mpigrobot/python | /P5/square.py | 152 | 4 | 4 | import math
def area_of_circle(x):
s=math.pi*x*x
return s
r=int(input('Բİ뾶'))
print(area_of_circle(r))
|
c5c8aee344ad853d5c7f77f0f0e9571cf00f71d7 | mpigrobot/python | /P4/p4-11.py | 213 | 4.0625 | 4 | try:
num1 = int(input('Enter the first number:'))
num2 = int(input('Enter the second number:'))
print num1/num2
except ValueError as e :
print 'You are wrong!'
finally:
print'The end.'
raise e
|
553b566c6561d1af6e1e00f6bcc1d6b157f0d134 | mpigrobot/python | /P4/p4-1.py | 196 | 3.96875 | 4 | try:
num1 = int(input('Enter the first number:'))
num2 = int(input('Enter the second number:'))
print num1/num2
except ZeroDivisionError :
print 'The second number cannot be zero'
|
d87ef401715c1dac44490f3508dd3db5ebb9be08 | sanapplegates/Python_qxf2_exercises | /employee.py | 417 | 3.65625 | 4 | class shopping_cart:
cart = 0
def __init__(self, item, total):
self.item = item
self.total = total
shopping_cart.cart += 1
def count(self):
print ("Total items %d" %shopping_cart.count)
def display_cart(self):
print ("item : ", self.item, ", total: ", self.total)
... |
42e25fed3a11b28f2bd4eb5070ce2ff7034eeda1 | sanapplegates/Python_qxf2_exercises | /bmi.py | 288 | 4.28125 | 4 |
#calculate the bmi of user
#user height in kg
print("Enter the user's weight(kg):")
weight = int(input())
#user height in metres
print("Enter the user's height(metre) :")
height = int(input())
#Body Mass Index of user
bmi = weight/(height*height)
print("bmi of user:",bmi)
|
303095966a5100ec69e9e3036b72ae09c869e0db | maddiecousens/Skills-Assessments | /functions/assessment.py | 7,415 | 4.375 | 4 | # PART ONE
# 1. We have some code which is meant to calculate an item cost
# by adding tax. Tax is normally 5% but it's higher in
# California (7%).
# Turn this into a function. Your function will pass in
# the default tax amount (5%), a state abbreviation, and the
# cost amount as parameters.
# If... |
4274c82a045ec95daf4c2d77a7954283829306d7 | xueer828/practice_code | /python/practice_py/find_2nd_num.py | 291 | 3.890625 | 4 | #find the 2nd largest number
def find_2nd(data):
if(len(data)<=1):
return -1
mx=data[0]
scd=-1
for x in xrange(1,len(data)):
if(data[x] > mx):
scd = mx
mx = data[x]
elif data[x] > scd:
scd = data[x]
return scd
if __name__ == '__main__':
d=[9,3]
print find_2nd(d) |
c4759dc87e930ac48c13ff16cde5290d71958471 | jasminks/ASTR260 | /astr260homedirectory/JasminS_EX2_p1b.py | 213 | 3.53125 | 4 | from math import exp
import math
a=1.
b=2.
x=1.
y=1.
for k in range (10):
if x > 0:
x=y*(a+x**2)
else:
x=
def g(x,y):
return b/(x**2+a)
for k in range (100):
x=f(x,y)
y=g(x,y)
print x,y
|
6d1ee772276ad42b49ff73d9487f13bfcf2fddc2 | jasminks/ASTR260 | /astr260astr260directory/SilvaJ_FINAL_Trap.py | 642 | 3.53125 | 4 | #pi=3.14159265
#c=3*(10**8)
#h=(6.636*(10**-34))
#k=1.38*(10**-23)
#k2= (2*pi*h*(1/c)*(1/c)*(k**4)*((1/h)**4))
#"k2" is constant beginning of problem
k2=8.66432176013e-09
def f(x):
from math import e
return (x**3)/((e**x) - 1.)
a=0.1
b=100
h=0.1
N=int((b-a)/h)
if N%2!=0:
N=N+1
s1 = 0.
s2 = 0.
st = 0.5*f(a... |
dd5b97ccd64384e8b7f2a71ac500eb4f8d006ee2 | jasminks/ASTR260 | /astr260homedirectory/trap.py | 146 | 3.59375 | 4 | import math
def f(x):
return math.exp(-x**2.)
N=30
A=0.0
B=3.0
h=(B-A)/N
s= 0.5*f(A)+0.5*f(B)
for k in range (1,N):
s+=f(A+k*h)
print (h*s)
|
ae243d7b52ffc7a999003db36d3fc61147382273 | petrov-lab/tuba-seq | /tuba_seq/pmap.py | 5,713 | 3.515625 | 4 | """Parallel (multi-threaded) map function for python.
Uses multiprocessing.Pool with error-resistant importing. There are two map
functions:
1) pmap(function, iterable) -> rapid fork-based multi-threaded map function.
2) low_memory_pmap(function, iterable) -> a more memory-efficient version
intended for functio... |
e129e27b4be8a5ad78bad47819fc9a60f10c410a | CMT040307/First | /First attempt.py | 657 | 3.8125 | 4 | def master():
#name and age
name = input("What is your name?")
age = int(input("How old are you?"))
print("Hello", name)
gender = input("Are you male or female?")
if gender.upper() == "MALE":
print("I am male too :)")
else:
print("Nice, I am male")
fav_food = input("Wha... |
38179717b10493e88e3763bd31da34707767ed05 | Alessandro-Francia/Compiti-per-10-12 | /es_3.py | 486 | 3.9375 | 4 | vocali = ["a","e","i","o","u", " "]
while True:
italiano = input ("dimmi una parola o una frase in italiano")
rovarspraket = ""
for lettera in italiano:
if lettera not in vocali:
rovarspraket += lettera + "o" + lettera
else:
rovarspraket += lettera
pr... |
71438d0ad0f123c96fb350704843653d31b79562 | bekahbooGH/Trees | /binary-trees.py | 4,571 | 4.125 | 4 | # Implement a Binary Tree data structure
class Binary_Node():
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def descendants_preorder(self):
print(self.data)
if self.left:
self.left.descendants_preorder... |
86a8f02df08ee0de1e9f3c613f096430637bd717 | kellywzheng/mycd | /mycd.py | 5,252 | 3.625 | 4 | import sys
import re
'''
Reduce multiple consecutive forward-slashes ("/") to one forward-slash
Remove any sequence that consists of a file name component (other than "." or ".."),
followed by "/", followed by the file name component ".."
'''
def simplify(directory):
while True:
old_dir = directory
... |
635cf28c6d55c10d3de2eade919273696764bdd1 | belochenko/python-algorithm | /codewars/snail_sort.py | 2,069 | 3.859375 | 4 | # Given an n x n array, return the array elements arranged from outermost elements to the middle element, traveling clockwise.
# array = [[1,2,3],
# [4,5,6],
# [7,8,9]]
# snail(array) #=> [1,2,3,6,9,8,7,4,5]
# For better understanding, please follow the numbers of the next array consecutively:
# arr... |
9889724ee39f3f308ef0e7356729fb4ed73ae0c9 | hanhan1280/mips241 | /test/big/generate-single-op.py | 1,942 | 3.578125 | 4 | #!/usr/bin/env python3
import fileinput
import struct
import sys
import signal
signal.signal(signal.SIGINT, lambda x, y: sys.exit(0))
def get_skel(s):
"""Get a tuple representing an instrution skeleton.
Args:
s: String of chars in {0, 1, x} of the skeleton
Returns:
Tuple (before, len... |
4be0f306a11be87ba2bea6c955205f19e993eb2d | yolkoo95/personal-web | /appstore/cachefile/generator.py | 1,137 | 3.828125 | 4 | # the program will generate greet message according to server/client time
# and select a wallpaper number randomly
# 'wallpaper_num' for select a wallpaper
# 'greet' will change with time
# 'date' to record date of time
# 'color_mode' to change the background color at night
import random, time
def generator():
# ... |
092af5d39ab8a46b6ca23b6c5d352c47ff780810 | nahuelv/frro-soporte-2019-11 | /practico_03/ejercicio_02.py | 1,022 | 3.609375 | 4 | # Implementar la funcion agregar_persona, que inserte un registro en la tabla Persona
# y devuelva de los datos ingresados, el id del nuevo registro.
import sqlite3
import datetime
from practico_03.ejercicio_01 import reset_tabla
def conexion ():
db = sqlite3.connect('C:\\Users\\Nahuel\\Desktop\\db_python.db')
... |
7f200a512c5821b826df1a6eec5259ef91484125 | nahuelv/frro-soporte-2019-11 | /practico_01_cvg/ejercicio_08.py | 547 | 4.21875 | 4 | """
Definir una función superposicion() que tome dos listas y devuelva True si tienen al
menos 1 miembro en común o devuelva False de lo contrario. Escribir la función
usando el bucle for anidado.
"""
lista_1 = ["a", "b", "c"]
lista_2 = ["b", "d", "e"]
def superposicion (lista1, lista2):
for i in range (0, len(... |
b88a715b7625b1b27f47e9cb6098e00e8e616f7e | lexruee/project-euler | /problem_9.py | 326 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc
"""
def main():
#TODO
pass
if __name__ == '__main__':... |
3c5f799e3a18974c27dea21f2f4f29d57746028b | lexruee/project-euler | /problem_25.py | 365 | 3.796875 | 4 | # -*- coding: utf-8 -*-
def fibonacci(n):
fn1 = 1
fn2 = 1
if n<2:
return fn1
for i in xrange(2,n):
fn = fn1 + fn2
fn2 = fn1
fn1 = fn
return fn1
print fibonacci(12)
i = 12
f = 0
while True:
f = fibonacci(i)
if len(str(f))==1000:
break
i +=1
... |
56e091e0215e5f1072d5b1f78eae6b6d783389e8 | chotu07/test1 | /test1.py | 3,164 | 4.09375 | 4 | # list is a collection of homogenous and heterogenous data types
l=[1,2,3,4]
type(l)
list=[1,2,3,4,5]
print(list[0])
#1.append is used to add one more
l=[1,2,3,4]
l.append(5)
print(l)
#2. extend is used to add or merge the two lists
l1=[1,2,3,4]
l2=[5,6,7]
l1.extend(l2)
print(l1)
#3.remove is used to elim... |
e0bddd821d6aae829c97600cc1ae62c614275d91 | HarshMule20/Python_Practices | /array/delete.py | 204 | 3.84375 | 4 | from array import *
arr=array('i',[])
for i in range(5):
a=int(input("Enter value= "))
arr.append(a)
print(arr)
for i in range(5):
if(i==2):
arr.remove(arr[i])
break
print(arr) |
2bad6c4aa30bef8d12f781f049c302556d57a8ae | HarshMule20/Python_Practices | /polymorphism/value.py | 193 | 3.671875 | 4 | class val:
def __init__(self,m1,m2):
self.m1=m1
self.m2=m2
def __str__(self):
return '{} {}'.format(self.m1, self.m2)
v1=val(4,5)
v2=val(6,4)
print(v1)
print(v2) |
29bdc660d07f403bd5610a1ec2e9a7f57e5b7cca | HarshMule20/Python_Practices | /class/compare_two_numbers.py | 363 | 3.8125 | 4 | class addition:
#def __init__(self):
# self.a = int(input("Enter the first value: "))
# self.b = int(input("Enter the second value: "))
def show(self,a,b):
self.a=a
self.b=b
if self.a==self.b:
return True
obj=addition()
if obj.show(7,7):
print("They are sa... |
0ebad3149b9a0b6366753473c6d2eddd630215a8 | Ammo-byte/Spirit-Trackr | /distancecalculator/spirittrackr.py | 1,869 | 3.734375 | 4 | import pandas as pd
import numpy as np
#Haversine Formula to calculate the distance between two points on a sphere, (code sample from Google)
def haversine_distance(latitude1, longitude1, latitude2, longitude2):
r = 6371
phi1 = np.radians(latitude1)
phi2 = np.radians(latitude2)
delta_phi = np.radia... |
13408d2173708d52c7f39c106995a546acb734a2 | OlegAvdienokTaskGit/Python-slices-tasks | /slice_6.py | 404 | 3.640625 | 4 | """
Дана строка, вывести все нечётные индексы.
Возьмём всю строку, и пройдемся по ней, начиная с 2 элемента, используя шаги (шаг в 2 символа).
Так как первый индекс [0], то отсчет идёт от первого символа.
"""
string = "0123456789"
print(string[1::2]) |
d9a2d697214d347ceb8c188dd339bfbf3e60ff10 | arkajitb/DataStructures | /secondweek_second.py | 1,439 | 4.0625 | 4 | # Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.
# Example 1:
# Input: S = "ab#c", T = "ad#c"
# Output: true
# Explanation: Both S and T become "ac"
# Example 2:
# Input: S = "ab##", T = "c#d#"
# Output: true
# Explanation: Both S and ... |
5203ff3707c3eccf69e8794cc7a41897538bde10 | BillBillBillBill/qlcoder | /755a/solve.py | 559 | 3.65625 | 4 | # coding: utf-8
import os
def find_max_size_file(dir_path):
dirs_and_files = os.listdir(dir_path)
dirs_and_files_path = map(lambda x: dir_path + "/" + x, dirs_and_files)
max_file_size_in_path = map(lambda x: (x, os.path.getsize(x)) if os.path.isfile(x) else find_max_size_file(x), dirs_and_files_path)
... |
3a539262ecf0f63733dd89c374b1ae57dd515977 | creichelt/100daysofpython_beginner | /003_treasureisland.py | 1,094 | 4.03125 | 4 | print("Welcome to Treasure Island!\n")
print("\nYour mission is to find the treasure...|")
print("\nWARNING: not intended for children!\n")
cross = input("You're at a cross road. Do you want to take 'left' or 'right'? ").lower()
if cross == 'left':
lake = input("You came to a lake. There is an island in the midd... |
ef5a89c7fccc71073f3d4809b89e73fe5a126983 | nortxort/tinybot-rtc | /apis/other.py | 3,454 | 3.671875 | 4 | """ Contains functions to fetch info from different simple online APIs."""
import util.web
def urbandictionary_search(search):
"""
Searches urbandictionary's API for a given search term.
:param search: The search term str to search for.
:return: defenition str or None on no match or error.
"""
... |
4227dcb300d4fa307993f81eb8decf6586738d99 | penroselearning/pystart | /ATM Machine.py | 1,224 | 4.0625 | 4 | PASSWORD='12345@'
account_balance=60000
attempts=3
pin=input("Enter your Account Pin:\n")
attempts -= 1
while pin!=PASSWORD:
if attempts > 0:
pin = input(f'''Sorry, the password is incorrect.You have {attempts} more attempt/s.
Please enter your Account Pin again:\n''')
attempts -= 1
else:
print(... |
70bccb7a493552961294f62cbd1d8a8bd9c7ae8b | penroselearning/pystart | /Arrival Time.py | 262 | 3.84375 | 4 | from datetime import datetime,timedelta
departure = datetime.now()
distance=5
speed=10
time = distance/speed
arrival = departure + timedelta(hours=time)
print(f"The boat Departure time: {departure.time()}")
print(f"The boat will Arrive at {arrival.time()}") |
2ff8a92f137f31da8bce56cb5444c86087d9f393 | Raviprakash-B/Python-basics | /list_comp.py | 253 | 3.796875 | 4 | #list comprehension
#LAMBDA
a = lambda x,y : x if x>y else y
print(a(2,5))
#MAP
n = [1,2,3,4,5]
print(list(map(lambda x: x**2,n)))
#FILTER
n = [1,2,3,4,5]
print(list(filter(lambda x: x>3,n)))
#REDUCE
n = [1,2,3,4,5]
print(reduce(lambda x,y: x+y,n))
|
588ea48e739e6762860446353ef2a693712f0083 | Raviprakash-B/Python-basics | /else.py | 79 | 3.609375 | 4 | x = 1
if x == 2:
print("not found")
else:
print("found",x)
#python3 else.py
|
918f441facb7f0e339d36bb9d2f599310e44d6f6 | saadkhan321/Project3_ND | /Python_Code/audit.py | 4,452 | 3.921875 | 4 | """
Your task in this exercise has two steps:
- audit the OSMFILE and change the variable 'mapping' to reflect the changes needed to fix
the unexpected street types to the appropriate ones in the expected list.
You have to add mappings only for the actual problems you find in this OSMFILE,
not a generaliz... |
9775d082ef3043fb020ffd1ac9137534069c6444 | adi-spec/nauka_pythona | /haslo.py | 342 | 3.5625 | 4 | #! /usr/bin/python
#haslo='woj'
haslo=input()
pwd=len(haslo)
#gwiazdki=
#secret=''
if pwd<3:
print("haslo za krotkie")
else:
for i in range(1, pwd -1):
print(haslo[0] + (pwd-2)*'*' + haslo[-1])
# break
#haslo = 'wojtek'
#gwiazdki = (len(haslo) - 2) * "*"
#secret = haslo[0] + gwiazdki + has... |
d3b38512fdc71b9953968731d12be52a176adb12 | idrisr/npr_puzzles | /10_31_parrot/creature.py | 1,665 | 3.984375 | 4 | """
From Michael Arkelian, of Sacramento, Calif.: Name a creature in six letters.
Move the first three letters to the end and read the result backward to name another creature.
Clue: If you break either six-letter word in half, each pair of three letters will themselves spell a word.
http://www.npr.org/templates/stor... |
91e717e2422ba6a54dcfef0de4292846b9fd1832 | Laavanya-Agarwal/Python-C2 | /Making functions/countWords.py | 271 | 4.3125 | 4 | def countWords():
fileName = input('Enter the File Name')
file = open(fileName, 'r')
noOfWords = 0
for line in file:
words = line.split()
noOfWords = noOfWords + len(words)
print('The number of words is ' + str(noOfWords))
countWords() |
3c54aa7bc9815de81888d9b40085067fa1cf218a | keryl/2017-03-24 | /even_number.py | 467 | 4.25 | 4 | def even_num(l):
# first, we will ensure l is of type "list"
if type(l) != list:
return "argument passed is not a list of numbers"
# secondly, check l is a list of numbers only
for n in l:
if not (type(n) == int or type(n) == float):
return "some elements in your list are... |
1c4d7118670c3d9a705ba5d14ad1a9aea618330f | Shahil98/Reccommender_Movie_System | /EDA.py | 1,593 | 3.734375 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df_main = pd.read_csv("training_ratings_for_kaggle_comp.csv")
df_movies = pd.read_csv('movies.dat',sep='::',names=["movie","movie_name","genre"])
df_main = pd.merge(df_main,df_movies,on="movie")
print()
print("=============... |
872ee49d185da0fec48939b43665c541099ff79e | anttesoriero/kg_anttesoriero_2021 | /main.py | 389 | 3.6875 | 4 | # Anthony Tesoriero - Kargo Summer 2020 Software Engineering Internship Assessment
import sys # Input from command line
s1 = sys.argv[1]
s2 = sys.argv[2]
if len(s1) != len(s2): # Check to see if strings are the same length. If not, print False
print(False)
elif len(set(s1)) != len(s1): # Check to see if s1 has... |
e698c9685c8fbf6d57ac79dfcc4d71f0ed1bf80e | Ayushree30/Python | /Encryption_software.py | 1,204 | 3.859375 | 4 | from tkinter import *
from tkinter import messagebox
import tkinter
import tkinter as tk
from Crypto.Cipher import AES
import os,base64
import rsa
window=tk.Tk()
msg=tk.Label(text="Encryption Software",width=20,height=2)
label=tk.Label(text="Enter Plaintext")
entry=tk.Entry(width=40)
def encryption():
#public and p... |
6aaa8b738d85fb7fa6a8ecf013f62dc565cb49f3 | kartavyabhatts30/Competitive-Coding-1 | /Problem1.py | 432 | 3.59375 | 4 | # your code goes here
def linMissingElem(nums):
for i in range(len(nums)):
if i == len(nums) - 1:
return i + 2
if nums[i] != i+1:
return i + 1
def binMissingElem(nums):
if nums[-1] == len(nums):
return len(nums)+1
l = 0
r = len(nums) - 1
while l < r:
m = l + (r-l)//2
if nums[m] > m+1:
... |
67e4f11eaa8ecc6402c5f85137f055875a5f3112 | co-devs/codeword-generator | /project/codewordgenerator.py | 5,209 | 4.40625 | 4 | #!/usr/bin/env python3
"""Code Word Generator
This script will provide the user with a randomly generated code word.
It requires the existence of several wordlists within the same folder in order
to make those code words.
This file can also be imported as a module and contains the following
functions:
* random_l... |
5db5b7d81bb4c0700add06486d81e592d8101dfd | EtMR/Data-Structures-and-Algorithms-Certificate-Course-Coursera- | /counting_inversion.py | 2,567 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created: Fri May 19 13:36:00 2020
@author: Etermeteor
Topic: counting_inversion
This script implements the counting inversion algorithm.
(week 2 - divide and conquer - algorithm 1)
"""
import random
import time
def count_inv(arr):
"""
Pesudocode:
count(... |
699e07824aea9ed37903c8a4e7daee1ed2ff4de3 | JLyndon/PLD-Assignment-02 | /UserDetails.py | 206 | 3.84375 | 4 | usr_name = input("Enter your name: ")
usr_age = input("Enter age: ")
usr_address = input("Enter your address: ")
print(f"\nHi, my name is {usr_name}. I am {usr_age} years old and I live in {usr_address}.") |
5826d676d257bfaa2bf72b13a1cf7105a2b1f79e | danny237/Python-Assignment3 | /binary_search.py | 1,087 | 3.671875 | 4 | """Implementation of Binary Search"""
def binary_search(list1, n):
"""
Functio for binary Search
Parameter:
list1(list): list of emement
n(int): number to be search
Return:
index(int): index of searched element
"""
L = 0
R = len(list1) - 1
whi... |
8bd5806dd9b01c9eb90592e7239e8662ae9f1af5 | danny237/Python-Assignment3 | /insertion_sort.py | 541 | 4.1875 | 4 | """Insertion Sort"""
def insertion_sort(list1):
"""function for insertion sort"""
for i in range(1, len(list1)):
key = list1[i]
j = i-1
while j >=0 and key < list1[j] :
list1[j+1] = list1[j]
j -= 1
list1[j+1] = key
return lis... |
db847c81696583b5f7497358984a09b7667e6617 | male524/Algorithms | /Week 4/toLowerCase.py | 579 | 3.90625 | 4 | # 709. To Lower Case
"""
Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase.
Example 1:
Input: "Hello"
Output: "hello"
Example 2:
Input: "here"
Output: "here"
Example 3:
Input: "LOVELY"
Output: "lovely"
"""
class Solution:
def toLowerCase(self, str: st... |
3fb94ff4bbb8804f5798884318f9b5174a820477 | male524/Algorithms | /Week 4/minTimeToVisitAllPoints.py | 2,182 | 3.9375 | 4 | # 1266. Minimum Time Visiting All Points
"""
On a 2D plane, there are n points with integer coordinates points[i] = [xi, yi]. Return the minimum time in seconds to visit all the points in the order given by points.
You can move according to these rules:
In 1 second, you can either:
move vertically by one unit,
move h... |
0227fd18303630931bddcb968fcf59461f0f6e09 | male524/Algorithms | /Week 13/Learn/getIntersectionNode.py | 1,129 | 3.5625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
from platform import node
class Solution:
def getIntersectionNode(self, headA: node, headB: node) -> node:
A = headA
B = headB
lenA = lenB = 1
if A... |
3f9c496c229700a9f0acf9bd80e21cc1618467f8 | male524/Algorithms | /Week 2/isValid.py | 2,367 | 4.03125 | 4 | # 20. Valid Parentheses
"""
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Example 1:
Input: s = "()"... |
ceca83f8d1a6d0dbc027ad04a7632bb8853bc17f | harshablast/numpy_NN | /nn.py | 2,183 | 3.734375 | 4 | import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def d_sigmoid(x):
return x * (1 - x)
def relu(x):
return x * (x > 0)
def d_relu(x):
return 1 * (x > 0)
class neural_network:
def __init__(self, nodes):
self.input_dim = nodes[0]
self.HL01_dim = nodes[1]
... |
3d2c83671779aae0c1226838d0b8dc6f73a90016 | milominderbinder22/cit129 | /wk5/cp_searchIt.py | 3,233 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 1 22:37:21 2018
"""
import json
def getCriteria(filename):
with open(filename,'r') as infile:
criteria=json.load(infile)
return criteria
def printProject(n):
keys=n.keys()
for i in keys:
print(i + ": ",n[i])
print("---------------... |
a92ddcd48a363dc8b7533fc30bc9ced4c0f901e7 | MoisesCatonio/Heap_Binary_Tree | /Heap.py | 2,131 | 3.53125 | 4 | class element:
def __init__(self, data=None, own_pos=None, father=None, left_son=None, right_son=None):
self.data = data
self.father = father
self.own_pos = own_pos
self.left_son = left_son
self.right_son = right_son
class heap:
def __init__(self):
self.tree = []... |
adfba4e45bc9ec9707eeda09767bfde152600426 | reachtoakhtar/data-structure | /tree/problems/binary_tree/diameter.py | 776 | 4.125 | 4 | __author__ = "akhtar"
def height(root, ans):
if root is None:
return 0
left_height = height(root.left, ans)
right_height = height(root.right, ans)
# update the answer, because diameter of a tree is nothing but maximum
# value of (left_height + right_height + 1) for each node
... |
c217c1c3b1af03e659f0a418b94684dd9e2cb372 | reachtoakhtar/data-structure | /tree/problems/binary_tree/maximum_sum_level.py | 2,082 | 4.09375 | 4 | __author__ = "akhtar"
def level_with_maximum_sum(root):
"""
Find the level with maximum sum in a binary tree.
:param BTreeNode root: The root of the tree.
:return: the level with maximum sum and the sum.
:rtype: tuple
"""
if root is None:
return
stack = [root]
level =... |
f137cb5b73c874f6d7efbf38e7245f3a7603126a | reachtoakhtar/data-structure | /tests/test_tree/problems/binary_tree/test_inorder_traversal.py | 3,414 | 3.5625 | 4 | __author__ = "akhtar"
import unittest
from tests.test_tree.utils import SampleBTree
from tree.problems.binary_tree.traversal_inorder import inorder_iterative
class TestInorderTraversal(unittest.TestCase):
def setUp(self):
return super().setUp()
def test_inorder_recursive(self):
print("T... |
623580ac962f92c1ce58be445c296c731b16a2fd | reachtoakhtar/data-structure | /tests/test_tree/problems/binary_tree/test_max_sum_level.py | 2,519 | 3.671875 | 4 | __author__ = "akhtar"
import unittest
from tests.test_tree.utils import SampleBTree
from tree.problems.binary_tree.maximum_sum_level import level_with_maximum_sum
class TestMaxSumLevel(unittest.TestCase):
def setUp(self):
return super().setUp()
def test_diameter(self):
print("TEST LEVEL... |
38c2c7c2a0ace1c174050b835855fc93d6709a1a | reachtoakhtar/data-structure | /tests/test_linked_list/problems/test_reverse_single_linked_list.py | 2,226 | 3.765625 | 4 | import unittest
from linked_list.exception import EmptyListError
from linked_list.lists import SingleLinkedList
__author__ = "akhtar"
from linked_list.problems.reverse_single_linked_list import \
reverse_single_linked_list
class TestReverseSingleLinkedList(unittest.TestCase):
def setUp(self):
self.... |
30982b383b30bc7c329196debc528bb91484155c | reachtoakhtar/data-structure | /tests/test_tree/problems/binary_tree/test_find_height.py | 1,929 | 3.890625 | 4 | __author__ = "akhtar"
import unittest
from tests.test_tree.utils import SampleBTree
from tree.nodes import BTreeNode
from tree.problems.binary_tree.find_height import find_height_iterative, \
find_height_recursive
class TestFindHeight(unittest.TestCase):
def setUp(self):
self.create_tree()
... |
fcaa579f2c5da9947e593f06227b1645e960d084 | reachtoakhtar/data-structure | /tests/test_tree/problems/binary_tree/test_find_size.py | 1,885 | 3.703125 | 4 | __author__ = "akhtar"
import unittest
from tests.test_tree.utils import SampleBTree
from tree.nodes import BTreeNode
from tree.problems.binary_tree.find_size import find_size_iterative, \
find_size_recursive
class TestFindSize(unittest.TestCase):
def setUp(self):
self.create_tree()
def crea... |
9c8fe55f7c3910b7dc73ee068c81c8276f350998 | rbirkaur23/Armstrong_Number | /armstrong_num.py | 219 | 3.953125 | 4 | n=int(input("Enter a number: "))
store=n
total=0
while n!=0:
last_digit=n%10
total=total+(last_digit**3)
n=n//10
if (total ==store):
print("Armstrong Number")
else:
print("Not an Armstrong Number")
|
a3690f36f56028ac4288ee264fb5d441d0f789e1 | demmmmmmi/psychopy2018 | /day.py | 300 | 4 | 4 | from datetime import datetime
print"what is the date you want to know the day, input yyyymmdd:)"
odate=raw_input()
print"The output 0 represent Monday :P and 1 mean Tuesday... you can +1 then that is the day you want to know:))"
odate = datetime.strptime(odate,'%Y%m%d' ).weekday()
print odate |
4ae028682e42184125c883e9bef12a4f80d74611 | hector81/Aprendiendo_Python | /CursoPython/Unidad10/Ejemplos/raise_levantar_excepciones.py | 440 | 3.890625 | 4 | def probable_execp(numero):
"""Función que sintácticamente está perfecta
pero no lógicamente
"""
numero = float(numero)
raiz = numero ** 0.5
if numero <0:
raise Exception("El dato introducido debe ser un número positivo")
else:
print(f"La raíz cuadrada del número... |
93c12f6ced3ca1b9d99a490e6e3e7d6551dbd58f | hector81/Aprendiendo_Python | /Bucles/Hexagono.py | 625 | 4.125 | 4 | numero = 0
cuadrado = ''
# bucle para poner numero correto
while numero < 1 :
# ponemos el numero
numero = int(input('Escribe el número '))
print()
if numero < 1:
print('El número debe ser positivo')
else:
numeroArriba = numero
while numeroArriba < ((numero*2) + 3)... |
a3d7e3651dfa1a7c87a4a08c2482479a1e060b69 | hector81/Aprendiendo_Python | /CursoPython/Unidad8/Ejemplos/funcion_datetime_datetime.py | 1,090 | 4 | 4 | '''
Con datetime puedes construir una fecha con su hora con el método constructor con el siguiente formato:
datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0).
Especificando la fecha y hora, sólo son obligatorios el año, el mes y el día.
'''
'''
una fecha 19 de juni... |
21cea9ddd51db449c503ea7e5b097d6e0b89930e | hector81/Aprendiendo_Python | /Bucles/Desglose_Cantidad_Monedas_Euros.py | 2,281 | 4.03125 | 4 | # Realiza un programa que proporcione el desglose en billetes y monedas de una
# cantidad entera de euros. Recuerda
# que hay billetes de 500, 200, 100, 50, 20, 10 y 5 ¤ y monedas de 2 y 1 ¤.
# Debes ✭✭recorrer✮✮ los valores de billete y moneda
# disponibles con uno o m´as bucles for-in.
def introducirCantidad()... |
ba1a94f3a0febbebcb813bd462e63179eaf1cc73 | hector81/Aprendiendo_Python | /CursoPython/Unidad8/Ejemplos/funcion_random_choice.py | 425 | 3.765625 | 4 | '''
La función choice(secuencia) elige un valor al azar en un conjunto de elementos.
Cualquier tipo de datos enumerables (tupla, lista, cadena, range) puede utilizarse
como conjunto de elementos.
'''
import random
#lista
print(random.choice(['win', 'lose', 'draw']))
#cadena
print(random.choice("estocadena"))... |
e76f3aaaeeea8f6372ee87a8263a350b51625bc8 | hector81/Aprendiendo_Python | /Excepciones/Ejercicio1_division_error_cero.py | 912 | 4.09375 | 4 | '''
EJERCICIOS EXCEPCIONES
1. Función que recibe dos enteros, a y b, y divide el mayor por el menor mostrando
un mensaje de error si es una división entre cero (ZeroDivisionError).
'''
def introducirNumero():
while True:
try:
x = int(input("Por favor ingrese un número: "))
... |
a341738e4c229e642ecb091b3c3ef8e471c484e9 | hector81/Aprendiendo_Python | /CursoPython/Unidad10/Ejemplos/excepcion_basica_general.py | 467 | 3.65625 | 4 | def excepcion_basica(numero):
try:
numero = float(numero)
calculo = numero ** 0.5
print(f"La raíz cuadrada del número {numero} es {calculo}")
except:
pass
print("Buen día.")
'''
Prueba en tu espacio de trabajo, excepcion_basica("6j"),
excepcion_basica(-90), ex... |
b9d59b5bd22207e7d7188fdfffa92f5acbccd82f | hector81/Aprendiendo_Python | /CursoPython/Unidad7/Ejercicios/ejercicio_II_u7.py | 1,171 | 4.53125 | 5 | '''
Lambda y map()
map() es una función incorporada de orden superior que toma una función e iterable como entradas, y
devuelve un iterador que aplica la función a cada elemento de la iterable. El código de abajo
usa map() para encontrar la media de cada lista en números para crear los promedios de la lista.
... |
7cb9b691fd986e01fca2d107ef040fa2661acf8c | hector81/Aprendiendo_Python | /Listas/IntroducirNotasAlumnos.py | 3,628 | 3.984375 | 4 | def introducirNumeroAlumnos():
while True:
try:
numeroAlumnos = int(input("Por favor ingrese el número de alumnos: "))
return numeroAlumnos
break
except ValueError:
print("Oops! No era válido. Intente nuevamente...")
# FIN FUNCION
def... |
b786cc73b8183d18f853c669c1edeedc93a8688e | hector81/Aprendiendo_Python | /Unidad9/Ejemplos/herencia/mascota.py | 363 | 3.734375 | 4 | # creamos la clase
class Mascota:
# declaramos el metodo __init__
def __init__(self):
self.nombre=input("Ingrese el nombre: ")
self.edad=int(input("Ingrese la edad: "))
def mostrar(self):
print("Nombre: ",self.nombre)
print("Edad: ",self.edad)
#----------hasta ... |
08be952345411637b829e6af9f3ff91c745225cd | hector81/Aprendiendo_Python | /CursoPython/Unidad5/Ejemplos/ejemplo3_if_else_anidados.py | 1,063 | 4.125 | 4 | '''
Durante el trimestre, un estudiante debe realizar tres exámenes. Cada examen tiene una calificación
y la nota total que recibe el estudiante es la suma de las dos mejores calificaciones.
Escribe un programa que lea las tres notas y determine cuál es la calificación total que recibirá el
estudiante.
Sola... |
0c9b52ac97b2fbdf3f5a0321f7cf36646986f4ab | hector81/Aprendiendo_Python | /Integer/DevolverDigitos.py | 391 | 4.09375 | 4 | def introducirNumero():
while True:
try:
x = int(input("Por favor ingrese un número par: "))
return x
break
except ValueError:
print("Oops! No era válido. Intente nuevamente...")
numero = introducirNumero()
numeroDigitos = len(str(num... |
0c8d83c250fa1300cde1e30bade521711b00199c | hector81/Aprendiendo_Python | /Integer/Introducir_Pares.py | 396 | 4.125 | 4 | def introducirNumero():
while True:
try:
x = int(input("Por favor ingrese un número par: "))
return x
break
except ValueError:
print("Oops! No era válido. Intente nuevamente...")
numero = 0
while numero%2 == 0:
numero = introdu... |
a5084140a8d49079bcbac4d8d6cc2cb27721ebab | hector81/Aprendiendo_Python | /Excepciones/Ejercicio2_texto_ruta_OSError.py | 1,117 | 4.125 | 4 | '''
EJERCICIOS EXCEPCIONES
2. Programa que itere sobre una lista de cadenas de texto que contienen nombres
de fichero hasta encontrar el primero que existe (OSError) [Pista: crear nuestra
propia función, existe_fichero(ruta), que devuelve True o False]
'''
# buscar fichero = Ejercicio2_texto_ruta_OSError.py
... |
9570e6bbbe210122e6a2611d19622fabafac0777 | hector81/Aprendiendo_Python | /CursoPython/Unidad6/Soluciones/ejercicio_I_u6 (2).py | 637 | 4.3125 | 4 | """Diseña un programa que genere un entero al azar y te permita introducir números para saber si aciertas dicho número.
El programa debe incluir un mensaje de ayuda y un conteo de intentos.
"""
import random
num = int(input("Introduce un número del uno a l diez: "))
aleatorio = random.randint(1,10)
while num != al... |
8c72ee9e300534e48b4f7ff9adad76e665e758b5 | hector81/Aprendiendo_Python | /CursoPython/Unidad7/Ejemplos/funcion_nonlocal.py | 558 | 4.15625 | 4 | '''
Si el programa contiene solamente funciones que no contienen a su vez funciones, todas las variables
libres son variables globales. Pero si el programa contiene una función que a su vez contiene una
función, las variables libres de esas "subfunciones" pueden ser globales (si pertenecen al programa
principa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.