blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
e2f8865b9eccdec2472b778826ef0d1fe8b32d6a | Rohiniwadi/1BM17CS078 | /lab8a.py | 348 | 3.671875 | 4 | def heapsort(a,n):
for i in range(3):
l=2*i+1
if l+1<n:
if a[l]<=a[i] and a[l+1]<=a[i]:
continue
else:
return False
elif l<n and a[l]<=a[i]:
continue
else:
return False
return True
l=[19,15,10,7,12,11... |
a370fc771fbce1fb6918619282cfed8ef0cae24b | mystery2828/AlgorithmsAndDataStructure | /Python/Algorithms/SearchingAlgorithms/no-of-occurrence-of-k.py | 1,362 | 3.546875 | 4 | def first(arr,l,r,k,n):
if l<=r:
mid = (l+r)//2
if (arr[mid] == k and (mid == 0 or k > arr[mid-1])):
return mid
elif (k>arr[mid]):
return first(arr,mid+1,n-1,k,n)
else:
return first(arr,l,mid-1,k,n)
return -1
def second(arr,l,r,k,n):
... |
916324c7fcc380fe505efa2e2c8c69aa8372a1c7 | andrewmwoodward/WeeklyProgramming | /Mathagrams/Mathagram.py | 1,737 | 3.546875 | 4 | # A.Woodward
# October 2016
# Mathagrams
# Instead of brute force I wanted to try a randomized solution solver
# Still might add bonuses
# Challenge #287 Intermediate
import math
import random
def create_list(input):
return_list = []
num_x = 0
trim_remain = [1,2,3,4,5,6,7,8,9]
for letter in input:
if not (... |
f3ff778147002322c07f7163b50fc1f8f825e220 | Pattrickps/Learning-Data-Structures-Using-Python | /data-structures/implement stack using linked list.py | 863 | 4.28125 | 4 | # Implement Stack using Linked List
class node:
def __init__(self,node_data):
self.data=node_data
self.next=None
class stack:
def __init__(self):
self.head=None
def push(self,data):
new_node=node(data)
new_node.next=self.head
self.head=new_node
def pop... |
8f3263d7c6d0c6850271577d17d7c712116bdead | Pattrickps/Learning-Data-Structures-Using-Python | /data-structures/queue using linked list.py | 1,296 | 4.34375 | 4 | #Implement Queue using Linked List
class node:
def __init__(self,node_data):
self.data=node_data
self.next=None
class queue:
def __init__(self):
self.head=None
def enqueue(self,data):
new_node=node(data)
new_node.next=self.head
self.head=new_node
def d... |
a31112ad72c5eca2812625b285eccb6ed0b6169b | Pattrickps/Learning-Data-Structures-Using-Python | /data-structures/inorder traversal.py | 406 | 4.0625 | 4 | # Tree traversals in a binary tree- A)INORDER TRAVERSAL
class Node:
def __init__(self,node_data):
self.data=node_data
self.left=None
self.right=None
def inorder(root):
if root:
inorder(root.left)
print (root.data)
inorder(root.right)
root=Node(1)
root.left=Nod... |
6ea65eec221b5c74ccd92c6475252dd9d525455c | samsledje/SaML-Lib | /NeuralNets.py | 1,953 | 3.734375 | 4 | """
Neural Networks
https://www.analyticsvidhya.com/blog/2017/05/neural-network-from-scratch-in-python-and-r/
"""
import numpy as np
from utils import *
def _sigmoid(x):
return (1 / (1 + np.exp(x)))
def _dev_sigmoid(x):
s = sigmoid(x)
return s * (1 - s)
class FeedForwardNet:
def __init__(self, input_... |
1963f8ac97c9bac53b650aff4b76512c7a8926dd | kevin-a-b/NullPointerSprint1 | /logtests.py | 2,431 | 3.703125 | 4 | from main import Project
import main
import unittest
console = Project()
class TestLogin(unittest.TestCase):
def test_login1(self): # No username and password entered, no user logged in. Should return error
self.assertEqual(console.command("login"), "Error")
def test_login2(self): # only username, ... |
9ad3ecc525fec0deea07cce48a83e392f578414e | Ganakol/Practice-Python | /TCS_DIgital_Casino_Problem.py | 429 | 3.84375 | 4 | def max_sum(arr):
current_sum = arr[0]
max_so_far = 0
for i in range(1,len(arr)):
if arr[i]>arr[i-1]:
current_sum = current_sum + arr[i]
else:
current_sum = arr[i]
max_so_far = max(max_so_far, current_sum)
return max_so_far
n = int... |
26af7b0d6789a51f7d02ac4898affb41c628f80c | dzhang379-school/interview-prep | /ernest.py | 2,446 | 3.578125 | 4 | exclusions = []
def phoneNumbers(length):
possibilities = range(10) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in exclusions:
possibilities.remove(i)
if length == 0:
exit(0)
for i in range(10):
if i == 4:
subNumbers('4', possibilities, length -1)
else:
... |
fedd9712befe12f4297d2838818707cb9d99769b | dzhang379-school/interview-prep | /knapsack_dp.py | 664 | 3.640625 | 4 | # A Dynamic Programming based Python Program for 0-1 Knapsack problem
# Returns the maximum value that can be put in a knapsack of capacity W
def knapSack(W, wt, val, n):
K = [[0 for x in range(W + 1)] for x in range(n + 1)]
# Build table K[][] in bottom up manner
for i in range(n + 1):
for w in ra... |
7377e1364a2ff9f51e576ed1fb5ce78d7f04abe1 | Tashsub/Luhn-Algortihm- | /checksumalgorithm.py | 1,704 | 4.03125 | 4 |
"""
add the digits of a number
"""
def adder(number):
sum_of_n = 0
for x in str(number):
sum_of_n += int(x)
return sum_of_n
"""
reverse the numbers
"""
def rev_num(number):
rev = list(reversed(number))
join = "".join(rev)
return join
"""
take the numbers at 1st, 3rd etc... and sum ... |
fbae25686e88498471c385033daf6d03ea74419d | mindyzwan/python-practice | /easy2/5.py | 197 | 4.0625 | 4 | def greeting():
name = input('What is your name? ')
if name.endswith('!'):
print(f'HELLO {name.upper()} WHY ARE WE SCREAMING?')
else:
print(f'Hello {name}.')
greeting() |
4ac777164accd7bbb1fb84bb4b55b39ea787cec6 | mindyzwan/python-practice | /easy4/9.py | 405 | 3.96875 | 4 | import math
def integer_to_string(num):
nums = {
1: '1', 2: '2', 3: '3', 4: '4', 5: '5',
6: '6', 7: '7', 8: '8', 9: '9', 0: '0'
}
digits = []
num_part = num
while num_part > 0:
digit = round((round(num_part / 10, 1) - (num_part // 10)) * 10)
digits.append(digit)
num_part -= digit
num_part //= 10
r... |
249b0868ddc1e62d04fffe1a11d9b2bb2f131511 | mindyzwan/python-practice | /easy1/3.py | 220 | 3.703125 | 4 | def digit_list(num):
return [int(digit) for digit in str(num)]
print(digit_list(12345) == [1, 2, 3, 4, 5])
print(digit_list(7) == [7])
print(digit_list(375290) == [3, 7, 5, 2, 9, 0])
print(digit_list(444) == [4, 4, 4]) |
d069b714d5b717442603f683647717772864c938 | mindyzwan/python-practice | /easy4/6.py | 311 | 3.828125 | 4 | def running_total(array):
total = 0
new_array = []
for num in array:
total += num
new_array.append(total)
return new_array
print(running_total([2, 5, 13]) == [2, 7, 20])
print(running_total([14, 11, 7, 15, 20]) == [14, 25, 32, 47, 67])
print(running_total([3]) == [3])
print(running_total([]) == []) |
fde3c6be1915e11568e8d3d75f24143892d5f319 | mindyzwan/python-practice | /easy1/5.py | 234 | 4.21875 | 4 | def reverse_sentence(string):
return ' '.join(string.split(' ')[::-1])
print(reverse_sentence('') == '')
print(reverse_sentence('Hello World') == 'World Hello')
print(reverse_sentence('Reverse these words') == 'words these Reverse') |
a54f6835c5e008614dbfb2949039962ee53686ed | whitecas18/swamp_website | /maze.py | 538 | 3.890625 | 4 | from location import location
class maze(location):
def __init__(self, name, adjacent, closeness):
super().__init__(
name,
adjacent,
'You are met with a dimly-lit corridor. Each step you take sets forth a resounding echo. Stopping to listen carefully, you hear a faint voice in the distance.'
)
self.cl... |
927f5c1a8e55f9391f1f622c4565c4b4d0184571 | KCMoser/db_snippets | /DBsingle_add.py | 380 | 3.796875 | 4 | import sqlite3
#connect to db
con = sqlite3.connect('test.db')
#create cursor object to execute sql statements
crsr = con.cursor()
#execute a statement
crsr.execute('''INSERT INTO table1 (first_name, last_name, Client, email, phone) VALUES (?, ?, ?, ?, ?)''', ('myfirstname', 'mylastname', 'Tecniplast', 'newemail', 'ne... |
fcfce792ecffcff46e0b1960cfa7d65c0a1b5b75 | sooyoungkim/flipped-python-intro | /7_Data_Structure.py | 6,583 | 4.25 | 4 | ########################################################
# namedtuple
# - tuple형태로 데이터 속성에 대한 'Data 구조체'' 저장
# - class 는 데이터 속성 + 행동을 정의할 수 있다.
# - 저장되는 data의 variable을 사전에 지정해서 저장
########################################################
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y... |
3f7b54339b267960bcf24165faae6d4fcc3a2718 | RobertGodin/CodePython | /ExempleWhileBreak.py | 337 | 3.890625 | 4 | """
Lire une suite d'entiers jusqu'à ce que l'entier 0 soit entré et afficher la somme
des entiers lus.Exemple du break.
"""
somme=0
while True:
chaine = input("Entrez un nombre entier, 0 pour terminer :")
if chaine != '0' :
somme = somme + int(chaine)
else:
break
print("La somme des entier... |
bed6b2db560b5510bd7ac687defd4a81ef25b90a | RobertGodin/CodePython | /ExempleBoucleIterNext.py | 278 | 4.09375 | 4 | # -*- coding: utf-8 -*-
une_liste = [3,1,2]
un_iterateur = iter(une_liste)
while True:
try:
suivant = next(un_iterateur)
print(suivant)
except StopIteration:
print("Fin de l'itérable")
break
for suivant in une_liste :
print(suivant) |
7c0f710c3f76793a0c5b3d15e642c67a556bd865 | RobertGodin/CodePython | /ExerciceWhile3.py | 297 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
@author: Robert
Lire dix entiers et en afficher la somme avec un while
"""
somme=0
compteur = 1
while compteur <= 10:
chaine = input("Entrez un nombre entier:")
somme = somme + int(chaine)
compteur = compteur+1
print("La somme des dix entiers est:",somme)
|
606005b2f1471b374f4bbafd67206d315f008bc4 | RobertGodin/CodePython | /CourbesComplexite.py | 335 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 25 20:18:46 2021
@author: vango
"""
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(1,11,1)
plt.plot(x,np.log(x), label="y=ln(x)")
plt.plot(x,x, label="y=x")
plt.plot(x,x*np.log(x), label="y=xln(x)")
plt.plot(x,x**2,label = "y=x*x")
plt.legend(loc='upper le... |
4547500d3483562b5571f168f677f713e4522955 | RobertGodin/CodePython | /Exercice1.py | 595 | 3.84375 | 4 | ''' Exercice1.py
Ce programme saisit trois entiers et en affiche la somme '''
# Saisir les deux chaînes de caractères qui représentent des nombres entiers
chaine1 = input("Entrez un premier nombre entier :")
chaine2 = input("Entrez un second nombre entier :")
chaine3 = input("Entrez un troisième nombre entier :")
#... |
92c1b69d6a8e6a284bc43ab14be3af32a5ec99a5 | soniabarroso28/ejercicios_python | /ejemplo_input_numeros_enteros.py | 280 | 3.921875 | 4 | numero1 = int(input("Dígame un número: "))
numero2 = int(input(f"Dígame un número mayor que {numero1}: "))
print(f"La diferencia entre ellos es {numero2 - numero1}.")
print(f"La suma entre ellos es {numero2 + numero1}.")
print(f"La division de ellos es {numero2 / numero1}.")
|
8fc847aa8f077e7abec82c05c2f109b324e489ef | code-lucidal58/python-tricks | /play_with_variables.py | 528 | 4.375 | 4 | import datetime
"""
In-place value swapping
"""
# swapping the values of a and b
a = 23
b = 42
# The "classic" way to do it with a temporary variable:
tmp = a
a = b
b = tmp
# Python also lets us use this
a, b = b, a
"""
When To Use __repr__ vs __str__?
"""
# Emulate what the std lib does:hand
today = datetime.date... |
ebe159650b9abc20718281becd65bd9736e2b201 | FCR001/Python | /pruebaTurtle.py | 744 | 3.984375 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import turtle
#create window and turtle
window = turtle.Screen()
babbage = turtle.Turtle()
#dibujamos el tallo y el centro
babbage.color("green", "black")
babbage.right(90)
babbage.forward(200)
babbage.left(180)
babbage.forward(300)
babbage.right(90)
babbage.color("black", "blu... |
be59c4c79a0058fa926385b8bc1d5402d4a116aa | bioinfo-ufsc/clostridium | /parser_ortho.py | 3,943 | 3.578125 | 4 | #!/usr/bin/python3
### Parser to count and extract paralogous and orthologous groups from OrthoMCL
# input_file is result from OrthoMCL
input_file = open("Cdiff_groups.txt", "r").read().splitlines()
# Create output files, where paralogous proteins of each organism will be stored
icc45 = open("Cdifficile_ICC45_par... |
9fddf453b9a9bce689b2880c40bbc05b2e17d15e | nickliqian/keep_learning | /KnowledgeMapping/spark/19_子图.py | 889 | 3.5625 | 4 | from graphframes.examples import Graphs
from pyspark import SparkContext
from pyspark.sql import SQLContext
sc = SparkContext("local", appName="mysqltest")
sqlContext = SQLContext(sc)
g = Graphs(sqlContext).friends() # Get example graph
# 创建子图
# Select subgraph of users older than 30, and relationships of type "fri... |
73e1e906883b6217a1aab4a19ed938510c4029dd | ilias511/Fundamentals_Lists-Functions | /Lists/exams/pirates.py | 419 | 3.578125 | 4 | nums = (input()).split()
added = [int(i) for i in nums]
is_five = False
output = []
average = sum(added) / len(added)
for n in added:
if len(added)<5:
print('No')
is_five = True
break
if int(n)>average:
output.append(n)
if is_five:
pass
else:
output.sort(reverse=True... |
df47d1d01a3f5fde250bd25f8bb32e7ad45d36de | ilias511/Fundamentals_Lists-Functions | /Final_exam-14-August/1st.py | 1,147 | 3.984375 | 4 | text = input()
command = input()
while command!='End':
possible_commands = command.split()
final_command = possible_commands[0]
if final_command == 'Translate':
char = possible_commands[1]
replacement = possible_commands[2]
text = text.replace(char,replacement)
print(text)
... |
ff22191fa9d905d77d77d9e6f2ab5608deb6df6f | ilias511/Fundamentals_Lists-Functions | /Functions/Perfect Number.py | 259 | 3.71875 | 4 | def perfect(num):
equal = 0
for i in range(1,num):
if num % i == 0:
equal+=i
if equal == num:
return 'We have a perfect number!'
else:
return "It's not so perfect."
num = int(input())
print(perfect(num))
|
0007bc093098f403304edc1be62f7541ccba04b0 | ilias511/Fundamentals_Lists-Functions | /dictionaries/Problem 1. Secret Chat.py | 818 | 3.875 | 4 | message = input()
command = input()
while command!= 'Reveal':
splited = command.split(':|:')
first = splited[0]
sec = splited[1]
if first == 'InsertSpace':
message_new = list(message)
message_new.insert(int(sec),' ')
message = ''.join(message_new)
print(message)
el... |
a65c12d957d56bc0e127d00c6896c5580d6520a4 | ilias511/Fundamentals_Lists-Functions | /text-processing/1st.py | 360 | 3.703125 | 4 | usernames = input().split(', ')
pr = []
for name in usernames:
if 3<=len(name)<=16:
is_valid = True
for ch in name:
if not ch.isdigit() and not ch.isalpha() and not '-' in name and not '_' in name:
is_valid = False
break
if is_valid:
p... |
467335edf1eafb7cdcf912fe46a75d3f6c712c08 | ugo-en/some-python-code | /extra_old_code/square.py | 326 | 4.5 | 4 | # Step1: Prompt the user to enter the length of a side of the square
length = int(input("Please Enter the LENGHT of the Square: "))
# Step2: Multiply the length by itself and assign it to a variable called area
area = length * length
# Step3: Display the area of the square to the user
print("Your area is: ",... |
3653c4987ee75687f3ad08710e803d8724ad244e | ugo-en/some-python-code | /extra_old_code/bmi_calcuator.py | 680 | 4.375 | 4 | #Opening remarks
print("This app calculates your Body Mass Index (BMI)")
#Input variables
weight = float(input("Input your weight in kg but don't include the units: "))
height = float(input("Input your height in m but don't include the units: "))
#Calculate the bmi rnd round off to 1 decimal place
bmi = weight / (hei... |
72d67c1ccb8703467153babbd8baae6c15ca226a | ankurt04/ThinkPython2E | /chapter4_mypolygon.py | 1,086 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 2 10:45:14 2017
@author: Ankurt.04
"""
#Think Python - End of Chapter 4 - In lessson exercises
import turtle
import math
bob = turtle.Turtle()
def square(t, length):
i = 0
while i <= 3:
t.fd(length)
t.lt(90)
i +=1
... |
ccbd62956120dd5eb7d117ea4cd0947fd24f3974 | ankurt04/ThinkPython2E | /chapter15_exercises.py | 947 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 8 09:27:12 2017
@author: Ankurt.04
"""
#Ex15.1
def point_in_circle(cir, dx, dy):
distance = (((dx - circle1.center.x) ** 2) + ((dy - circle1.center.y) ** 2)) ** 0.5
if distance <= circle1.radius:
print("Point is within the circle")
... |
206a4c693fce92a235fbe2e35fde377fa536c780 | ankurt04/ThinkPython2E | /chapter16_inchapter.py | 2,545 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 8 10:13:17 2017
@author: Ankurt.04
"""
#Ex 16.1
def print_time(time):
print("Given time is %.2d:%.2d:%.2d" % (time.hour, time.min, time.sec))
def main():
class Time:
"""Represents the time of the day
attributes: hour, ... |
292cdbcf34da5aac6935d5741aee51ebf9722b49 | Jilroge7/holbertonschool-web_back_end | /0x01-python_async_function/4-tasks.py | 592 | 3.671875 | 4 | #!/usr/bin/env python3
"""
Learning async/await and asyncio
"""
import asyncio
from typing import List, Any
task_wait_random = __import__('3-tasks').task_wait_random
async def task_wait_n(n: int, max_delay: int) -> List[float]:
"""
takes in 2 int arguments, spawn wait_random n times specified max_delay
""... |
c9e6c8d4c5944f1a96690e28fb0b97bb3813e9ba | Jilroge7/holbertonschool-web_back_end | /0x02-python_async_comprehension/0-async_generator.py | 363 | 3.53125 | 4 | #!/usr/bin/env python3
"""
aync generator practice
"""
import asyncio
import random
from typing import Generator
async def async_generator() -> Generator[float, None, None]:
"""
coroutine loop 10x, asynchronously wait 1 second, then yield random number
"""
for i in range(10):
await asyncio.sl... |
29b3b4aec6c7a67309c1c444232060adc6ab609e | Jilroge7/holbertonschool-web_back_end | /0x0D-NoSQL/11-schools_by_topic.py | 401 | 3.765625 | 4 | #!/usr/bin/env python3
"""
function that returns the list of schools having specific topic
"""
def schools_by_topic(mongo_collection, topic):
"""
return result of search string topic in collection
"""
query_topic = {'topics': topic}
if mongo_collection:
return mongo_collection.find(query_t... |
1db8a2274966f8fa4516c0841302fcc8165eff0f | Jilroge7/holbertonschool-web_back_end | /0x04-pagination/1-simple_pagination.py | 1,519 | 3.953125 | 4 | #!/usr/bin/env python3
"""
Task 1, python simple pagination func
"""
import csv
import math
from typing import List
index_range = __import__('0-simple_helper_function').index_range
class Server:
"""Server class to paginate a database of popular baby names.
"""
DATA_FILE = "Popular_Baby_Names.csv"
de... |
3de0d33e1299915f1f330e3521daa4f51867f1e5 | gvlawrence/MQ-ACST890 | /A1T1/T1Q4.py | 635 | 3.90625 | 4 | """ Ass1 Task1 Q4 - GregL 83186557 - T1Q4.py """
import sys
# first parm should be the required Fibonacci number
if len(sys.argv) >= 2:
fibnum = int(sys.argv[1])
else:
fibnum = int(input("Required Fibonacci number = "))
# display actual parms in use
print("argv=%s fnum=%s \n" % (sys.argv,fibnum... |
6e823fead5a492d332b2b6ef2071a8de57f1a7b3 | Programacion-Algoritmos-18-2/2bim-clase-01-josuerojas19 | /ejercicio-clases/manejo-excepciones/principal.py | 351 | 3.609375 | 4 |
try:
edad = input("Ingrese su edad: ")
edad = int(edad)
print('Su edad es %d' % (edad))
# except NameError as e:
# print('Existe un error: %s' % (e))
#except ValueError as e:
# print('Existe un error (%s): %s' % (e.__class__, e))
#except Exception as e:
# print('Existe un error (%s): %s' % (e.__class__, e))
exc... |
0c5fa3bc1d2a1104926e09bd4f18b44dc379654a | vitoriaguidines/python | /a.py/lista 2 URI/Q5.py | 135 | 3.59375 | 4 | a = [4, 5, 6]
b = a * 2
c = a[:]
d = a
a[0] = 'a'
b[0] = 'b'
c[0] = 'c'
d[0] = 'd'
print(a)
print(b)
print(c)
print(d) |
1027a1dfb4e517faaad03d60477a0ba917215262 | ammshahin/UVa-Problems | /p12250 - Language Detection.py | 540 | 3.5625 | 4 | t = 1
while True:
s = str(input())
if s == '#':
break
elif s == 'HELLO':
print('Case {}: ENGLISH'.format(t))
elif s == 'HOLA':
print('Case {}: SPANISH'.format(t))
elif s == 'HALLO':
print('Case {}: GERMAN'.format(t))
elif s == 'BONJOUR':
print('Case {}: FR... |
fe4affe34dad1cdb13149fd9ea74d20a85dd1ad0 | seanbergman98/Foobar-Problems | /running_with_bunnies.py | 3,834 | 3.546875 | 4 | def isBetter(next_sol, sol):
#Method to check if a given set of saved bunnies is better than another set of saved bunnies, with both sets already ordered
if len(next_sol) > len(sol):
return True
elif len(sol) > len(next_sol):
return False
for i in range(len(next_sol)):
if... |
ea551758341013aec269dfcddfd679688faa7725 | delfinoz571/pythonworkspace | /3-if.py | 2,567 | 4.0625 | 4 | # IF
# weather = input("오늘 날씨는 어떄요?")
# if weather == "비" or weather == "눈":
# print("우산을 챙기세요")
# elif weather == "미세먼지":
# print("마스크를 챙기세요")
# else:
# print("준비물 필요없어요")
# temp = int(input("기온은 어때요?"))
# if 30 <= temp:
# print("너무 더워요. 나가지 마세요")
# elif 10 <= temp and temp < 30:
# print("괜찮은 날씨에요... |
553fdf08c6102c6c016e8464f6ebce3e26a2b96a | robj137/advent_of_code | /2016/day01.py | 1,448 | 3.796875 | 4 | import datetime as dt
from collections import defaultdict
class Traveler:
def __init__(self):
self.position = 0 + 0j
self.direction = 0 + 1j
self.visited = {}
self.visited_twice = []
def get_position(self):
return self.position
def get_distance(self, val):
return abs(int(val.real)) + abs... |
b990af5efe5429ed5079a40d38fb5ff4c88081d4 | zeinabss/Zeinab_Sobhani_Test | /Python/Overlap Check.py | 899 | 3.71875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[15]:
# isoverlap function checks whether two priveded ranges in the format of two tuple range1=(x1,x2) and range2=(x3,x4) overlap
def isoverlap(range1,range2):
ranges=[range1,range2]
try:
ranges=sorted(ranges, key=lambda x:x[0])
x2=ranges[0][1]
... |
f1a1d08fa7136a770ca44fbe8dfbf8ffc4eee38e | katelevshova/py-algos-datastruc | /Problems/strings/anagrams.py | 1,721 | 4.15625 | 4 | # TASK
'''
The goal of this exercise is to write some code to determine if two strings are anagrams of each other.
An anagram is a word (or phrase) that is formed by rearranging the letters of another word (or phrase).
For example:
"rat" is an anagram of "art"
"alert" is an anagram of "alter"
"Slot machi... |
630c9a6b42c6bcb0e5be91c7aef410c634e6114e | katelevshova/py-algos-datastruc | /Problems/design/shape_area.py | 1,388 | 3.921875 | 4 | from math import pi
class Shape:
def area(self):
print("Calculate area:")
return 0
def get_2decimal_digits(self, number):
print("[Shape]->get_2decimal_digits: ")
formatted_result = '{:0.2f}'.format(number)
return formatted_result
class Rectangle(Shape):
def __in... |
34a3db5600ba10bbb56f367a3e940ef5d47bdedb | katelevshova/py-algos-datastruc | /Course3/p3_rearrange_array_digits.py | 9,350 | 4 | 4 | """
TASK3:
Rearrange Array Elements
Rearrange Array Elements so as to form two number such that their sum is maximum. Return these two numbers.
You can assume that all array elements are in the range [0, 9]. The number of digits in both the numbers
cannot differ by more than 1. You're not allowed to use any sorting fu... |
ca3c26abae8e09c5009586871ebbd884fed30f37 | katelevshova/py-algos-datastruc | /Course3/p1_sqrt.py | 5,291 | 4.5 | 4 | """
TASK1:
Finding the Square Root of an Integer
Find the square root of the integer without using any Python library. You have to find the floor value of the square root.
For example if the given number is 16, then the answer would be 4.
If the given number is 27, the answer would be 5 because sqrt(5) = 5.196 whose fl... |
e56c99d2a16d2819a3209bf3cc27ea86ae2c8fa0 | katelevshova/py-algos-datastruc | /Problems/stacks_queues/balanced_parentheses.py | 1,469 | 4.125 | 4 | """
((32+8)∗(5/2))/(2+6).
Take a string as an input and return True if it's parentheses are balanced or False if it is not.
"""
class Stack:
def __init__(self):
self.items = []
def size(self):
return len(self.items)
def push(self, item):
"""
Adds item to the end
"... |
852e3df4043c9c2a07b9f650381f646a1c6a02aa | khmelyukovsd/Python_algorithms | /Lesson 7/Lesson7_task2.py | 1,302 | 4.0625 | 4 | # 2. Отсортируйте по возрастанию методом слияния одномерный вещественный массив,
# заданный случайными числами на промежутке [0; 50).
# Выведите на экран исходный и отсортированный массивы.
import random
import operator
# генерация случайного массива
array = [round(random.uniform(0, 49), 2) for _ in range(10)]
print(... |
c7e7ad7590aa6573fc458b71350f586ddc423635 | khmelyukovsd/Python_algorithms | /Lesson 7/Lesson7_task1.py | 1,357 | 3.96875 | 4 | # 1. Отсортируйте по убыванию методом пузырька одномерный целочисленный массив,
# заданный случайными числами на промежутке [-100; 100).
# Выведите на экран исходный и отсортированный массивы.
# Примечания:
# a. алгоритм сортировки должен быть в виде функции, которая принимает на вход массив данных,
# b. постарайтесь с... |
f63a7e6e0d738b9d1e6a076aa9171f106f5f8da1 | khmelyukovsd/Python_algorithms | /Lesson 3/Lesson 3.Task 4.py | 915 | 3.765625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# Урок 3. Задача 4. Определить, какое число в массиве встречается чаще всего
# Создание массива
from random import randint
a = [randint(1, 100) for _ in range(100)]
print (f'Исходный массив:\n{a}')
count = 0
# Поиск повторяющегося элемента
for i in range(len(a)):
... |
b5edf0fd3ae765c933bfbad9352f43aa0f3ed893 | cifpfbmoll/practica-2-python-juliajacaDAM | /pr2_ej4.py | 435 | 4.0625 | 4 | '''
Práctica 2. Ejercicio 4
Diagrama para calcular el mayor de dos números
'''
print('''
Vamos a calcular cuál es el mayor de los siguientes dos números
--------------------------------------------------
''')
num_1 = float(input("Introduce el primer número \n"))
num_2 = float(input("Introduce el segundo número \n"))
... |
92b673572d01975b56265b738af2b72c7a852e69 | Thunae/CSSI | /Anagrams/factorial.py | 168 | 4.15625 | 4 | def factorial(num):
if num == 1:
return 1
return num * factorial(num-1)
number = int(raw_input("Factorial of what number? "))
print(factorial(number))
|
2a36785fee17e7fede104738b10e72bca575ee4d | NerdJain/Python | /common_list.py | 1,123 | 3.921875 | 4 | def main():
print("...List 1...")
n = int(input("Enter no. of items: "))
l1 = []
for i in range(n):
num = input("Enter element: ")
l1.append(num)
print("...List 2...")
n = int(input("Enter no. of items: "))
l2 = []
for i in range(n):
num = input("Enter element: ")
l2.append(num)
p... |
9ed7f2895fe7f8bc8a84cfd3fc2a82b5eaf6b849 | NerdJain/Python | /append_list.py | 924 | 3.984375 | 4 | def main():
print("...List 1...")
n = int(input("Enter no. of items: "))
l1 = []
for i in range(n):
num = input("Enter element: ")
l1.append(num)
print("...List 2...")
n = int(input("Enter no. of items: "))
l2 = []
for i in range(n):
num = input("Enter element: ")
l2.append(num)
for it... |
6f495c6f055867f3df8bd832470e3697e89427e9 | NerdJain/Python | /search_tuple.py | 566 | 4.1875 | 4 | def main():
l = []
n = int(input("Enter no. of elements in tuple: "))
for i in range(n):
l.append(input("Enter Element: "))
t1 = tuple(l)
se = input("Enter search element: ")
if se in t1:
print(f"{se} is in {t1}")
else:
print(f"{se} not in {t1}")
if __name__ == '__main__':
main()
... |
c3eb966884f205bcedde72fdc392bd42f3fd0692 | NerdJain/Python | /test_turtle.py | 871 | 3.90625 | 4 | import turtle
screen = turtle.Screen()
# this assures that the size of the screen will always be 400x400 ...
screen.setup(400, 400)
# ... which is the same size as our image
# now set the background to our space image
screen.bgpic("scan pic.jpg")
# Or, set the shape of a turtle
screen.addshape("iss.jpg"... |
a993875781e4f2e0a10076c51eca37123d9fe368 | zhongweiy/jsinterpreter | /jstokens.py | 5,753 | 3.6875 | 4 | # JavaScript: Numbers & Strings
#
# handling Numbers, Identifiers and Strings in a simpler version.
#
# a JavaScript IDENTIFIER must start with an upper- or
# lower-case character. It can then contain any number of upper- or
# lower-case characters or underscores. Its token.value is the textual
# string of the identifi... |
2857dc0bab5d0c8743d2fee55b78d365584e1f23 | LINFUICHIN/guessnumber | /guessnumber.py | 449 | 3.71875 | 4 | import random
start = int(input('請輸入開始數字: '))
end = int(input('請輸入結束數字: '))
r = random.randint(start, end)
count = 0
while True:
count += 1
num = int(input('請輸入數字: '))
if num == r:
print('你猜對了!')
print('你總共猜了', count, '次')
break
elif num > r:
print('你輸入的數字大於答案')
elif num < r:
print('你輸入的數字小於答案')
print('... |
edbf5b7c45bd43917d56099a020e9f82a21a0f64 | nsuryateja/python | /exponent.py | 298 | 4.40625 | 4 | #Prints out the exponent value eg: 2**3 = 8
base_value = int(input("enter base value:"))
power_value = int(input("enter power value:"))
val = base_value
for i in range(power_value-1):
val = val * base_value
#Prints the result
print(val)
#Comparing the result
print(base_value ** power_value)
|
290f2f97a19fdad0649621108fef6ae017a9368e | nsuryateja/python | /topgear_justify.py | 1,227 | 3.796875 | 4 | import sys
if len(sys.argv)> 1:
filename = sys.argv[1]
width = sys.argv[2]
with open('filename','r') as f:
text = f.read()
total = len(text)
def justify(text,width):
helper = ''
for i in range(len(text)-1):
if (text[i].isalpha() or text[i]== ' '):
helper = hel... |
40d7afc7856181d439ae5064d17162047d7ce13d | nsuryateja/python | /pr1_imdbScraper.py | 1,259 | 3.796875 | 4 | #This following code scrapes the IMDB website for top 250 indian movies and creates a dictionary of movie name,rating and its year of release
from bs4 import BeautifulSoup
import requests
source = requests.get("https://www.imdb.com/india/top-rated-indian-movies/?sort=rk,asc&mode=simple&page=1").text
soup = BeautifulSo... |
625b8fe76200201c5a8779fa533ef52452919853 | nsuryateja/python | /vowelFinder.py | 494 | 3.828125 | 4 | string = 'the fragrance of flowers spreads only in the direction of the wind'
lis = string.split()
print(lis)
vowel = 0
num = []
for i in range(len(lis)):
k = lis[i]
for r in k:
if (r== 'a' or r== 'e' or r== 'i' or r== 'o' or r== 'u' ):
vowel = vowel +1
num.append(vowel)
vowel = 0
p... |
10d842964f84c5fd57aa9984f2fe46d744b637bd | nsuryateja/python | /returnOnceDigit.py | 305 | 3.96875 | 4 | def returnOnceDigit(num):
div = 1
for i in range(1,len(str(num))):
div = div * 10
num = int(num)
while(not num < 10):
num = num % div
div = div/10
return int(num)
print('enter a num:')
print(returnOnceDigit(input()))
|
15deafc391a92162901fb9af5a3092c02d2832a9 | nsuryateja/python | /noOfSubsequencesRecursion.py | 257 | 3.953125 | 4 | def subsequences(text):
if len(text) == 1:
return 1
elif len(text) == 2:
return 3
else:
return subsequences(text[1:len(text)])*2+1
no_of_subs = subsequences('abcdef')
print(no_of_subs)
|
15552d8dbb4542118407481bf046d5db787c750c | nsuryateja/python | /BankAccount_Flask.py | 602 | 3.734375 | 4 | #Udemy Flask Tutorial Python level 2 OOP Exercise
class Account():
def __init__(self,owner,bal = 0):
self.owner = owner
self.bal = bal
def deposit(self,amount):
self.bal += amount
return self.bal
#Cant withdraw more than balance...obvio!
def withdraw(self,amount):
if amount <= self.bal:
... |
fab7e80d4059181b36f7b15aceb67eb304f40458 | Cookiee-monster/nauka | /Scripts/Ćwiczenia/dates_cleaning.py | 712 | 3.75 | 4 | import re
def split_elements(date):
date_regex = re.compile(r'''
(\d+) # pierwszy człon daty
(\W) # separator
(\d+) # drugi człon daty
(\W) # separator
(\d+) # trzeci człon daty
''', re.VERBOSE)
dates_raw = date_regex.search(date)
return dates_... |
72f018f1d298e3240255f4c10051aedf320f996a | Cookiee-monster/nauka | /Exercism/python/yacht/yacht.py | 1,590 | 3.578125 | 4 | # Score categories
# Change the values as you see fit
YACHT = "Yacht"
ONES = 1
TWOS = 2
THREES = 3
FOURS = 4
FIVES = 5
SIXES = 6
FULL_HOUSE = "Full_house"
FOUR_OF_A_KIND = "Four_of_a_kind"
LITTLE_STRAIGHT = "Little_straight"
BIG_STRAIGHT = "Big_straight"
CHOICE = "Choice"
def score(dice, category):
if category in... |
0c8a0a4a0838ae85d6f6cfc647e379fb82f455b6 | Cookiee-monster/nauka | /Exercism/python/perfect-numbers/perfect_numbers.py | 330 | 3.71875 | 4 | def classify(number):
if number <= 0:
raise ValueError("Number cannot be 0 or negative.")
divisors = [div for div in range(1, number) if number % div == 0]
if sum(divisors) == number:
return "perfect"
elif sum(divisors) > number:
return "abundant"
else:
return "d... |
68dd411100373bca02fa2b0de18354f9c92f82e8 | Cookiee-monster/nauka | /Exercism/python/palindrome-products/palindrome_products.py | 1,671 | 3.921875 | 4 | def largest(min_factor, max_factor):
if min_factor > max_factor:
raise ValueError("Min factor cannot be bigger than max factor")
list_of_palindromes, list_of_values = palindromes(min_factor, max_factor)
if len(list_of_values) == 0:
return None, []
all_factors_pairs = [palindrome[1] f... |
0d760ab53b3b0cb5873064ab0ed74b54a1962db1 | Cookiee-monster/nauka | /Scripts/Python exercises from GIT Hub/Ex 9.py | 567 | 4.34375 | 4 | #! Python 3
# Question 9
# Level 2
#
# Question£º
# Write a program that accepts sequence of lines as input and prints the
# lines after making all characters in the sentence capitalized.
# Suppose the following input is supplied to the program:
# Hello world
# Practice makes perfect
# Then, the output should be:
# HEL... |
c6d8591335d276a86b0567f86e764cde472c701b | Cookiee-monster/nauka | /Scripts/I'm feeling Lucky.py | 770 | 3.578125 | 4 | #! python 3
import sys, webbrowser, requests, bs4
print('Googling...') # display text while downloading the Google page
wyszukiwanie = str(input("What are You looking for? "))
"""
if len(sys.argv) > 0:
res = requests.get('http://google.com/search?q=' + ' '.join(sys.argv[1:]))
res.raise_for_status()
else:
... |
07bcdd9aaac7533bca685a1e4bc17f21db3733da | Cookiee-monster/nauka | /Scripts/Python exercises from GIT Hub/Ex 19.py | 1,181 | 4.6875 | 5 | #! Python 3
# Question:
# You are required to write a program to sort the (name, age, height) tuples by ascending order where name is string,
# age and height are numbers. The tuples are input by console. The sort criteria is:
# 1: Sort based on name;
# 2: Then sort based on age;
# 3: Then sort by score.
# The priority... |
7f4b0fa838f18db30c0bbd26ffc4cde8c26118bf | Cookiee-monster/nauka | /Exercism/python/beer-song/beer_song.py | 1,307 | 4 | 4 | def recite(start, take=1):
current_beer = start
result = []
while take != 0:
if current_beer > 2:
result += \
["{0} bottles of beer on the wall, {0} bottles of beer.".format(str(current_beer)),
"Take one down and pass it around, {} bottles of beer on the ... |
acb259ba48e088defb2e83f2f30719bbf0d4e453 | Cookiee-monster/nauka | /Scripts/ptvpuzzle_grid.py | 1,488 | 3.921875 | 4 | import time
start = time.time()
def check_step(sequence, grid_size):
"""
:param sequence: set of already founded paths
:param grid_size: size of the network
:return: new sequence of paths, one step longer
"""
new_sequences = []
# Step to the East is only possible if path contain more s... |
1a48070e72b8510dcd71f58b2f60ac5c67aa4da5 | Cookiee-monster/nauka | /Exercism/python/isbn-verifier/isbn_verifier.py | 500 | 3.671875 | 4 | import re
def verify(isbn):
isbn_as_a_list = re.findall("([0-9X])", isbn)
if len(isbn_as_a_list) != 10:
return False
result = 0
multiplier = 10
for digit in isbn_as_a_list:
if digit.isdigit():
result += int(digit) * multiplier
elif digit == "X" and multiplier == ... |
da160a4834a1ae4c43fcf5f4e6e6ad9f01e107db | OualidOuaquad/competitive-programming | /hackerrank/Climbing_the_Leaderboard.py | 2,770 | 3.75 | 4 | import math
import os
import random
import re
import sys
# Complete the climbingLeaderboard function below.
# def insert(list, n):
# # Searching for the position
# for i in range(len(list)):
# if list[i] < n:
# index = i
# break
# # Inserting n in the list ... |
4520804449227ecd63cfca73cecb387ec0d9cdd7 | IreriVIkki/PasswordLocker | /users.py | 6,094 | 4 | 4 | #!/usr/bin/env python3.6
import pyperclip
from accounts import Account
class User():
users_list = {}
# Initialization function for creating a new instance of thr User class
def __init__(self, first_name, last_name, email, password, accounts):
self.first_name = first_name
self.last_name ... |
3cc4ed17d8cd399672c78f9952f59a008df4ec94 | AdamJonsson/KTH-DD1315-ProgrammingTechniques | /Labbar/lab4/lab4.py | 5,119 | 3.671875 | 4 | from terminalColor import bcolors
class Account:
def __init__(self, name, money, pin_code):
self.name = name
self.money = money
self.pin_code = pin_code
self.transactions = []
print("Skapade ett nytt konto")
def __str__(self):
accountOwner = "Konto: " + self.na... |
3b21c47dfe2d133931e69f60a327d349c85f8557 | AdamJonsson/KTH-DD1315-ProgrammingTechniques | /Labbar/lab1/uppgift5.py | 453 | 4.03125 | 4 | import sys, math
def myFunction():
mathValue = math.pi**2/6
sumValue = 0
n = int(input("\nn: "))
for i in range(1, n + 1):
sumValue += 1/(i**2)
print("Math value: ", mathValue)
print("Sum value: ", sumValue)
print("The difference between the values", (mathValue - sumValue), "\n")
... |
b3a3edd51183ffb0c796e60042c4ad4ddc36fe27 | AdamJonsson/KTH-DD1315-ProgrammingTechniques | /Labbar/lab1/AdamsTools.py | 446 | 3.75 | 4 | def longNameGenerator(nameToRepeat, iterations, newline = False):
theLongName = ""
for i in range(0, iterations):
theLongName += nameToRepeat
if newline:
theLongName += "\n"
return theLongName
def requiredInput(inputText, errorText):
while True:
userInput = input(in... |
5c1abfd320d03854d56f2887a00233c497b61140 | uralbash/Python-lectures | /lec3/LPTHW/ex15.py | 861 | 3.71875 | 4 | # coding: utf-8
# Чтение текстовых файлов
from sys import argv
script_name, file_name = argv
# посмотрите в документацию
# клчевые слова: open, file
txt_file = open(file_name)
print "Вот содержимое файла %s:" % file_name
print txt_file.read()
print "Введите назвавние файла:"
file_name = raw_input('> ')
print "Во... |
9da72aa7413871625a8108d1a9451afad0e84bbd | uralbash/Python-lectures | /lec3/LPTHW/ex11.py | 1,145 | 3.90625 | 4 | # coding: utf-8
# Ввод с терминала
print "Сколько вам лет?"
age = raw_input()
print "Какой у вас рост (в метрах)?"
height = raw_input()
print "Сколько вы весите (в килограммах)?"
weight = raw_input()
print "Вам %r лет/года. Ваш рост: %r метра и вы весите %r кг." % (
age, height, weight
)
# выражение float() исп... |
a5e600249ff4d8e16ba26dcfe54a9d4d87a192ca | codingkai001/py-codes | /socket/get_location.py | 816 | 3.75 | 4 | """使用谷歌地理编码API获取地址的经纬度"""
import requests
import http.client
import json
from urllib.parse import quote_plus
def geocode1(address):
parameters = {'address': address, 'sensor': 'false'}
base = 'http://maps.googleapis.com/maps/api/geocode/json'
response = requests.get(base, params=parameters)
answer = r... |
30b716754dfa8a65cff0492ee4bc7e307582e02b | chunthebear/snake-pygame | /snake.py | 2,174 | 3.671875 | 4 | import pygame
import random
# initialize pygame
pygame.init()
#set display size
gameDisplay = pygame.display.set_mode((800,600))
#name of display
pygame.display.set_caption("hello snake")
gameExit = False
clock = pygame.time.Clock()
start_x = 300
start_y = 300
start_x_change = 0
start_y_change = 0
snakeList = ... |
18271e7c69b49c2a3d347af5da7817fb0c12b488 | SureshG13/Sorting_Algorithms_In_Python | /Selection_Sort.py | 505 | 4.03125 | 4 | #Implementation of Selection Sort in Python
#Finding minimum value from the left to right and replace with currect value
l=[40,29,30,55,70,18,35]
for i in range(len(l)-1):
for j in range(i+1,len(l)):
if l[j]<l[i]:
l[i],l[j]=l[j],l[i]
print(l)
# Or you can do it in another way
def selection... |
b46eccc8c945fb4d9c58e8423893212a1debb6d6 | wangcx0305/Reinforcement-Learning | /assignment5/regret.py | 846 | 3.828125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 24 15:11:23 2017
@author: wangchunxiao
"""
class Regret:
def __init__(self, optimal_expected_reward):
self.optimal_expected_reward = optimal_expected_reward
self.expected_reward_best_arm = 0
self.expected_cumul... |
2403f43b6c8ee6970f348303ad28c2575162aef9 | BartoszKopec/wsb-pios-python | /src/2020-05-07_raport.py | 1,068 | 3.875 | 4 | def simpleFunc(): #najprostsza kontrukcja funkcji
print("foo") #jej ciało musi być wcięte w prawą stronę tak jak ma to miejsce w przypadku pętli lub instrukcji warunkowych
simpleFunc()
def add(a, b): #dowolna ilość parametrów może być przekazana. Są one traktowane jako zmienne lokalne
return a+b #standardowa ... |
ee60f505a48bf96be0fcba27b66255a5846253ca | Fantendo2001/FORKERD---University-Stuffs | /CSC1001/hw/hw_0/q1.py | 297 | 3.671875 | 4 | def sq(a,b):
if abs(int(a ** .5) - a ** .5) < 0.0000000001 and abs(int(b ** .5) - b ** .5) < 0.00000000001:
return True
else:
return False
x, y = 3, 2
for i in range(100):
if i != 0:
x = 3 * x + 4 * y
y = 2 * x + 3 * y
print(x,y)
print(sq(x,y)) |
e4966aa9218d3aa06830bdb2a49508f4bb1f93e7 | Fantendo2001/FORKERD---University-Stuffs | /CSC1001/lec/Linked.py | 604 | 3.734375 | 4 | class Node:
def __init__(self, e):
self.value = e
self.prev = None
self.nxt = None
class LinkedList:
def __init__(self):
self.header = Node(None)
self.trailer = Node(None)
def __len__(self):
return 0
def show(self):
def insert(self, val, i):
... |
d863997509ddc1bcf91d2217c99681040b2855a6 | Fantendo2001/FORKERD---University-Stuffs | /CSC1001/hw/hw_0/q2.py | 354 | 4.21875 | 4 | def display_digits():
try:
# prompts user for input
num = int(input('Enter an integer: '))
except:
print(
'Invalid input. Please enter again.'
)
else:
# interates thru digits of number and display
for dgt in str(num):
print(dgt)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.