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 |
|---|---|---|---|---|---|---|
400fca61b673ee522754c59257527031bfd6835f | athreygonella/SudokuSolver | /sudokuAPI.py | 1,850 | 3.5625 | 4 | import json
from urllib.request import urlopen
import time
import SudokuStructure
def getSudokuData(difficulty, size):
requestURL = f'http://www.cs.utep.edu/cheon/ws/sudoku/new/?size={size}&level={difficulty}'
with urlopen(requestURL) as response:
source = response.read()
data = json.loads(sour... |
04bbe642d41620970a31ada8106a34a090cc3a05 | allya-tt/TowersHanoi | /towers.py | 599 | 3.875 | 4 | def towers(n, a, b, c):
if n == 1:
print("Move ring ", n, ' from ', a, ' rod to ', b, ' rod.', sep='')
else:
towers(n-1, a, c, b)
print("Move ring ", n, ' from ', a, ' rod to ', c, ' rod.', sep='')
towers(n - 1, c, b, a)
return ''
def main():
n = int(input('Enter the nu... |
1bd8eae15f6647194e3277eae9ce223c3d0a834b | jonag-code/python | /electric_car_module.py | 746 | 3.875 | 4 | #Note in this module we import the class Car() from
# another module! ...i.e. the file "car_module.py"
from car_module import Car
class Battery():
def __init__(self, battery_size):
self.battery_size = battery_size
def describe_battery(self):
print("This car has a %s-kWh battery." %self.battery_size)
def get_... |
6ec9cf2b3adfe58b1e235d1a250348d913cf4a40 | jonag-code/python | /matplot_examples.py | 205 | 3.734375 | 4 | import matplotlib.pyplot as plt
X= [x**2 for x in range(10)]
Y= [y**3 for y in range(10)]
plt.plot(X,Y, 'ro')
plt.plot(X,Y, linestyle = 'solid')
#plt.plot(Y, 'b')
plt.axis([0,100,0,1000])
plt.show()
|
28d231a0a4e9f1a42c968643e77bd1598e0da992 | jonag-code/python | /dictionary_list_tuples.py | 1,675 | 4.25 | 4 | List =[x**2 for x in range(5)]
Dictionary = {0:'zero', 1:'one', 2:'four', 3:'nine', 4:'sixteen'}
Tuple = tuple(List)
#The following doesn't work as with lists: Tuple2 =(x**2 for x in range(10)).
#Also the entries of tuples cannot be modified like in lists or dictionaries.
#This is useful when storing import... |
43d5fdc1a48355a93064fe1c4698212c669059b0 | jonag-code/python | /dictionaries_from_lists.py | 1,115 | 3.96875 | 4 | #THE CODE AFTER THIS ONE IS THE SUPERIOR VERSION:
d = {1:'one',2:'two'}
print("This is the old d: \n %s \n" %d)
Keys = list(d.keys())
Values = list(d.values())
for i in range(len(d)):
d[Values[i]] = d[Keys[i]]
del d[Keys[i]]
print("This is the new (overwritten) d: \n %s \n" %d)
#Here we create two lists a... |
adf3d388f6ee280d9961c48b24eb9b6dde0d736d | sm2774us/octo-barnacle | /sorting/mergesort/mergesort.py | 904 | 3.875 | 4 | # mergesort prototype
from json import dumps
def mergesort(input, count):
if count < 2:
return input
al = count / 2
bl = count - al
a = mergesort(input[:al], al)
b = mergesort(input[al:], bl)
c = []
ai = 0
bi = 0
i = 0
# do the actual sorting.
while i < count:... |
835bc99a74cdc7e8acb462eb90c6805c5fab1fda | ChrisLolz/DMOJ-solutions | /CCC 12 J2.py | 249 | 3.953125 | 4 | a,b,c,d = int(input()),int(input()),int(input()),int(input())
if a > b > c > d:
print("Fish Diving")
elif a < b < c < d:
print("Fish Rising")
elif a == b and a == c and a == d:
print("Fish At Constant Depth")
else:
print("No Fish")
|
e8489802585b380809fab0151f5794f4c8608848 | ChrisLolz/DMOJ-solutions | /Sorting.py | 150 | 3.6875 | 4 | n = int(input())
list = []
for i in range(n):
x = int(input())
list.append(x)
list.sort()
for i in range(len(list)):
print(list[i])
|
2b0dee01a43a35beab96bcad9fccad0714fd3ea7 | zkrOzer/Algoritmo-A- | /main.py | 6,951 | 3.546875 | 4 | #Clase nodo, permite g,h,f
class Node():
#constructor del nodo
def __init__(self, x = 0, y = 0, padre = None):
self.x = x
self.y = y
self.padre = padre
self.g = 0
self.h = 0
self.f = 0
def __eq__(self, other):
return (self.x == other... |
807cedb7901fd5331d72dfb086c17382389bed8f | eduardez/AlfonsoGarcia | /utils.py | 1,438 | 3.53125 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import json
PATH_TO_JSON = './file_list.json'
def isInList(hash):
'''
Comprueba si una cancion esta en la lista de canciones
descargadas comparando su hash.
'''
for k in jsonRead():
if k == hash:
return True
else:
... |
bc219761bc6dd7e98d15dada2a682d66a9ce2ae1 | DavidQM/Clase_Python | /Raiz_cubo.py | 436 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Fecha: 23/06/2017
Autor: David Q
Titulo: Raiz cubica
Descipcion: Aplicacion de Ciclos simples - sln de problemas
"""
print("Raiz Cubica")
n=int(input("Ingrese el numero del que desaea conocer la raiz cubica"))
cubo=0
i=0
while(cubo < abs(n)):
i+=1
cubo=i**3
if(cubo==abs(n)):
... |
3f818ac4017b9c70089646bc0cdfeac5ef65c0d3 | MoizesCBF/exercicios_cev | /desafios/desafio6.py | 467 | 3.96875 | 4 | # Crie um algoritmo que leia um número e mostre o seu dobro, triplo e raiz quadrada
a = int(input("Número: "))
print('Dobro de {0} = {1}: '.format(a, a * 2))
print('Triplo de {0} = {1}: '.format(a, a * 3))
print('Raiz Quadrada de {0} = {1}: '.format(a, a ** 0.5))
# OU
n = int(input('Digite um número: '))
d = n * 2
t... |
525e8f5934198a7116f3eb36c87fc16a7b661b73 | pat-hills/Payroll-Enterprise-Web-Application | /appusers/utils.py | 279 | 3.84375 | 4 | import datetime
def greetings():
currentTime = datetime.datetime.now()
currentTime.hour
if currentTime.hour < 12:
greet = 'Good morning'
elif 12 <= currentTime.hour < 18:
greet = 'Good afternoon'
else:
greet = 'Good evening'
return greet |
b831921bf3f540ef6e9a6a8957720757feda3e46 | theparadogs/Python | /Calculator.py | 780 | 4.125 | 4 | print("===============================================")
#masukan input dari user
print("Selamat Datang di Program Kalkulator sederhana")
enter = input("klik enter untuk lanjut : ")
print("Program ini dibuat oleh Felix Rizky Lesmana")
enter = input("klik enter untuk lanjut : ")
print("================================... |
70f6efe66f5a93ccb77bbeee149524c22c53d1f3 | yytjdduq/coin2021 | /game.py | 282 | 3.78125 | 4 | print("비트코인")
print("디카르고 24%다")
print("1. 몰빵 2. 존버")
a = input("입력: ")
print("당신이 입력한 값은? ", a)
#만약에 1 번이면 개떡락
if a == "1":
print("개떡락")
#만약에 2 번이면 개떡상
if a == "2":
print("개떡상")
|
f5cacef883a4d672132f48b6b3e17a0792bc3788 | Tatuska23/Czechitas-Kurz_1 | /podminky.py | 471 | 3.640625 | 4 | #x = int(input('Zadej cislo:'))
#if x % 2 == 0:
# print(x, 'je sude')
#else:
# print(x, 'je liche')
names_list = ['Jiří', 'Jan', 'Marie', 'Petr', 'Jana', 'Josef', 'Pavel', 'Martin', 'Jaroslav', 'Tomáš', 'Eva', 'Miroslav', 'Hana', 'Anna', 'Zdeněk', 'František', 'Václav', 'Michal', 'Lenka', 'Kateřina']
x = input... |
de9a668400bd67b96f5621163441872121bbb9f9 | Tatuska23/Czechitas-Kurz_1 | /du1.py | 52 | 3.578125 | 4 | n=5
while n>0:
n=n-1
print(n)
print('Hura')
|
a99060d84e1bf7c0f38d615482035a64a4a62d00 | JoshCheung/CMPS5P | /PythonProj/Hw2/hw2.py | 2,394 | 3.640625 | 4 | #cmps5
#hw2
#1485979
#1a
def max2a(a, b):
if a > b:
return a
else:
return b
# max2a(7,3) == 7
# max2a(3.5, 6.5) == 6.5
#1b
def max2(a, b):
return a if a > b else b
#max2(3, 4) == 4
#max2(10, 9) == 10
#max2(8, 8) == 8
#1c
def max3(a, b, c):
return max2(a, b) if max2(a, b) > c else c
#1d
#max3(7,... |
8de38fdb7c723281a7bceaf68f86fb09d6523b42 | Armenianchess/flask-survey-documents | /surveys.py | 1,386 | 3.578125 | 4 | class Question:
def __init__(self, question, choices=None, allow_text=False):
if not choices:
choices = ["Yes", "No"]
self.question = question
self.choices = choices
self.allow_text = allow_text
class Survey:
def __init__(self, title, instructions, questions):
... |
4e5a34a5a570d67a33a414124f62dd3b498e06a2 | Robin-Andrews/Serious-Fun-with-Python-Turtle-Graphics | /Chapter 8 - The Classic Snake Game with Python Turtle Graphics/2. basic_snake_movement.py | 1,362 | 4.25 | 4 | # Import the Turtle Graphics module
import turtle
# Define program constants
WIDTH = 500
HEIGHT = 500
DELAY = 400 # Milliseconds between screen updates
def move_snake():
stamper.clearstamps() # Remove existing stamps made by stamper.
# Next position for head of snake.
new_head = snake[-1].copy()
... |
cf283d2be373b64de60796a41088c3bcdd54c64c | Robin-Andrews/Serious-Fun-with-Python-Turtle-Graphics | /Chapter 14 - Python Turtle Graphics and Tkinter GUI Programming/turtle_tkinter3.py | 580 | 3.75 | 4 | import turtle
import tkinter as tk
def do_stuff():
for color in ["red", "yellow", "green"]:
my_lovely_turtle.color(color)
my_lovely_turtle.right(120)
def press():
do_stuff()
if __name__ == "__main__":
root = tk.Tk()
canvas = tk.Canvas(root)
canvas.config(width=600, height=200)
... |
6f56940c9a42f5b4a078be4adb7cddd28b539b43 | carmencitamb9/ejercicio_M2 | /M1_E1_P4.py | 1,484 | 4.09375 | 4 | """"**********************************
Autor : Bristela Muñoz Burgos
Carrera : Ingeniería en Informática
Ramo : Programación Básica
Modulo : M1-E1
Ejercicio 4 : Con lo aprendido hasta el momento, realiza un programa que de manera totalmente matemática
(ocupando solo lo visto hasta el momento), mue... |
ec0af5bcde099c9a9695d6ec4d8f4f231b13ce7e | rizqo46/refactory-assignment | /logic_test/leapyear.py | 695 | 4.15625 | 4 | # In the Gregorian calendar, three conditions are used to identify leap years:
# - The year can be evenly divided by 4, is a leap year, unless:
# - * The year can be evenly divided by 100, it is NOT a leap year, unless:
# - - # The year is also evenly divisible by 400. Then it is a leap year.
def leapyear(a, b):
i... |
501ca8c5a71b67cd7db14e7577be41fcd6646fd7 | shantanusharma95/LearningPython | /DataStructures/priority_queue.py | 2,988 | 4.25 | 4 | import sys
class node:
def __init__(self,data,priority):
self.data=data
self.priority=priority
self.next=None
class queue:
def __init__(self):
self.Head=self.Tail=None
self.queueSize=0
#adds a new value to queue, based on priority of data
#this will make enqueu... |
523b14700cff770198ddcdb4434029d060da5482 | z-no/euler | /problem_3.py | 755 | 3.734375 | 4 | """
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
"""
import math, sys
def is_prime(n):
"""
Stolen from: https://en.wikipedia.org/wiki/Primality_test#Pseudocode
"""
if n <= 1:
return False
elif n <= 3:
return True
elif n % 2 == 0 or n % 3 == 0... |
03464f244fef8b36d23779122b1760c22516ba11 | karanramani/pythonProject-unittest-calculator | /src/Calculator.py | 1,594 | 3.65625 | 4 | from CsvReader import CsvReader
import math
def addition(a, b):
a = float(a)
b = float(b)
c = a + b
return c
def subtraction(a, b):
a = float(a)
b = float(b)
c = b - a
return c
def multiplication(a, b):
a = float(a)
b = float(b)
c = a * b
return c
def division(a, b):
... |
db9aea2a9fc6cd892b5902d55f4653602e45e4c2 | jbloemker97/Python-Challenges | /alphabet_soup.py | 179 | 3.84375 | 4 | '''
Create a function that takes a string and returns a string with its letters in alphabetical order.
'''
def alphabet_soup(txt):
return "".join(sorted(list(txt.lower())))
|
47b1dc61f43c82c0bdc7f44240b4907d690a1cba | jbloemker97/Python-Challenges | /missing_num.py | 257 | 4 | 4 | '''
Create a function that takes a list of numbers between 1 and 10 (excluding one number) and returns the missing number.
'''
def missing_nums(lst):
try:
for num in range(1,11):
index = lst.index(num)
except:
return num |
359d0a96f1cd936c172d309e3ec2f3aebcafee13 | jbloemker97/Python-Challenges | /how_many_vowels.py | 226 | 4.03125 | 4 | '''
Create a function that takes a string and returns the number (count) of vowels contained within it.
'''
def count_vowels(txt):
vowels = ['a', 'e', 'i', 'o', 'u']
return len([i for i in list(txt) if i in vowels])
|
cece5c1532726ae761daf3f1801f3c646ce05413 | moqiguzhu/Online-Judge | /leetcode-python/weeklycontest/weeklycontest150/maxLevelSum.py | 1,051 | 3.65625 | 4 | # Definition for a binary tree node.
from collections import deque
import math
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxLevelSum(self, root: TreeNode) -> int:
if root is None:
return 0
q ... |
b70459e98c0523815944cd2dcf7d6f3471639cf6 | moqiguzhu/Online-Judge | /leetcode-python/Trie/WordSearchII.py | 3,696 | 3.703125 | 4 | from typing import List
from collections import defaultdict
class TrieNode():
def __init__(self):
self.children = defaultdict(TrieNode)
self.is_leaf = 0
class Trie():
def __init__(self, words):
self.root = TrieNode()
self.build(words)
def insert(self, word):
node... |
bbbff1b1e6f66a265966cc9c3fca7f64f00ca937 | moqiguzhu/Online-Judge | /leetcode-python/weeklycontest/193/problem1.py | 490 | 3.5 | 4 | from collections import defaultdict, deque, Counter
from typing import List
import math
import copy
import random
import numpy as np
import bisect
import inspect
import unittest
class Solution:
def runningSum(self, nums: List[int]) -> List[int]:
res = [0] * (len(nums) + 1)
for idx, e in enumerate(... |
1677a6378c55b1cbd648fec26e12f46d135a081e | DHvanTienhoven/Advent_of_Code | /AoC 2019/03december/puzzle.py | 2,874 | 3.578125 | 4 | from input import cable_one, cable_two
#part one:
def path_cable(cable):
path = ['0, 0']
lr_direction = 0
ud_direction = 0
for dir in cable:
dir_dim = dir[0]
dir_num = int(dir[1:])
steps = range(0, dir_num + 1)
for step in steps:
if dir_dim == 'R':
... |
75aabaa6d32ed8d921a2f546ef6853e3adc3684f | Thancred-Waters/software | /Web/testDemo/dao/userDao.py | 2,483 | 3.5625 | 4 | import pymysql
# 打开数据库连接
class DataBase():
def reconnect(self):
host = "localhost"
# host = "192.168.0.142"
self.conn = pymysql.connect(
host=host,
user="root",
# password="tsh08040313",
password="zctest",
database="test",
... |
0a2a37ae0f928d3b342e768f63bb1f67fbce2cd7 | epitts1013/CSC-442-Chimera | /Binary-Decoder/Binary.py | 655 | 3.53125 | 4 | import sys
from textwrap import wrap
def main():
content = getContent()
binaryConvert(content, 7)
binaryConvert(content, 8)
def getContent():
for line in sys.stdin:
return line.rstrip()
def binaryConvert(content, length):
text = ""
if (len(content) % length) == 0:
wrap... |
42e5fc44d7f312cf2805d1d33ea9fef7c4b10fbe | blohrman/knot-theory | /python/generate_gauss.py | 2,565 | 3.671875 | 4 | from util import arr_to_str
import numpy as np
'''
Disclaimer: There is a chance this is done in a way too complicated fashion lol
Function to take a Gauss Code and "relabel" it such that the crossings begin with 1.
Used in the function to generate all possible Gauss Codes.
@author Ben Jammin'
'''
def relabel(arr):
... |
31b70b0d82b92fe38b2bb8e4a592dd5aef8baafd | Bmurphmedia/Map-Reduce-Practice | /problem1.py | 1,105 | 3.84375 | 4 | import MapReduce
import sys
# Create an inverted index, dictionary where each word is associated with a list of document identifiers
# inwhich the word appears.
# Output should be a (word, document ID list) tuple where word is String,
# and documen Id list is a list of Strings
"""
Word Count Example in the Simple Py... |
5d4fa5ca82a1168d6d73f5e2eb2862f4a9ee3952 | yangzhenxing369/PythonLearning | /helloworld.py | 131 | 3.59375 | 4 | print "hello world"
print "hello world"
for x in ['x', 'a', 'b', 'c']:
print x
for x in xrange(1,10):
print "china"
|
74cc65a4847d386acf38ce1099db93c3f48195b5 | lsindelar/bowling_kata | /bowling.py | 3,826 | 3.765625 | 4 | class Frame:
"""
Frame class.
Represents a single frame.
"""
def __init__(self, rolls):
"""
Initialises Frame.
Parameters
----------
rolls : :obj:`str`
string of the rolls.
"""
if len(rolls) == 1:
... |
2213d1a707f9d7b0e3a15fd77df217e51af401d0 | Kabur/KR-Qualitative-Reasoning-Sink-Modeling | /State.py | 1,054 | 3.53125 | 4 | class State:
def __init__(self, id, quantities,reason=""):
self.id = id
self.quantities = quantities
self.reasons=[reason]
def printSelf(self):
print("*" * 100)
for quantity in self.quantities:
print(quantity.id, ": ", quantity.value, " ", quantity.derivati... |
f9e1f5188a275db3e4005700d5f4e279bf4f045c | muhannadbm/Python | /challenge-problems/exercise3/test.py | 2,158 | 3.53125 | 4 | """
Test script for the blackjack scorer
Author: Walker M. White
Date: July 30, 2019
"""
import introcs
import func
def test_bjack():
"""
Tests procedure for function bjack().
"""
print('Testing bjack()')
result = func.bjack(())
introcs.assert_equals(0,result)
# Test the individ... |
314d6ea80bd0429099feeeb0e8aefb4cae36fe19 | INGourav/python | /fib.py | 302 | 4.03125 | 4 | def fib(n):
if n == 0:
return 0 # First case if n is 0 then return 0
elif n == 1:
return 1 # second case if n is 1 then return 1
return fib(n-2) + fib(n-1)
item_to_calculate = int(input("what fibonnaci item would you like to calculate? "))
print(fib(item_to_calculate)) |
08951c8a90dc3bffde4ce992e89a15ff0ba31acf | adudjandaniel/Fractions | /lib/fraction/fraction.py | 2,313 | 4.1875 | 4 | class Fraction():
'''A basic fraction data type in python'''
def __init__(self, a=0, b=1):
self.a = a
self.b = b if b else 1
def __str__(self):
'''Converts the instance to a string'''
return "{}/{}".format(self.a, self.b)
def __repr__(self):
'''View of the inst... |
41f9eaee34956ebf3e6688ebca4d55b095552448 | yafiimo/python-practice | /lessons/11_ranges.py | 992 | 4.21875 | 4 | print('\nloops from n=0 to n=4, ie up to 5 non-inclusive of 5')
for n in range(5):
print(n)
print('\nloops from 1 to 6 non-inclusive of 6')
for n in range(1,6):
print(n)
print('\nloop from 0 to 20 in steps of 4')
for n in range(0, 21, 4):
print(n)
print('\nloop through list like a for loop')
food = ['cha... |
842079f591bef1485312dad98a8d44ad0cbace44 | yafiimo/python-practice | /lessons/27_writing_files.py | 941 | 4.125 | 4 | # must use 'w' as 2nd argument to write to a file, and file_name as first argument
with open('text_files/write_file.txt', 'w') as write_file:
text1 = 'Hello, I am writing my first line to a file using Python!'
print('Writing first line to file...')
write_file.write(text1)
# if you want to ammend a file, yo... |
831b72e4d735508717a21b778d171c81c6a20e74 | yafiimo/python-practice | /lessons/24_lambdas.py | 329 | 3.78125 | 4 | def initCap(word):
return word[0].upper() + word[1:]
sentence = ['hello', 'my', 'name', 'is', 'amad']
# Using a function already defined, in map
print(' '.join(list(map(initCap, sentence))))
# lambdas can be used as inline, anonymous functions
print(' '.join(list(map(lambda word: word[0].upper() + word[1:], sent... |
33a894372a9b31f0417bed82d5fec500370e3f0b | zerodayz/dailycoding | /Examples/Comprehensions.py | 416 | 3.6875 | 4 | def main():
evens = [2, 4, 6, 8, 10]
odds = [1, 3, 5, 7, 9]
evenSquared = [ e**2 for e in evens if e > 4 and e < 8 ]
print(evenSquared)
evensDict = {e: e+10 for e in evens}
print(evensDict)
oddsDict = {e: e+10 for e in odds}
print(oddsDict)
numbers = {k:v for number in (evensDict... |
34072bd99c3dd303d0ca2a05d2a1855bd548b796 | zerodayz/dailycoding | /Examples/Iterator.py | 731 | 3.984375 | 4 | import itertools
def functionA(x):
return x <= 3
t = itertools.count(1, 2)
list1 = []
# 1, 5, 9
while next(t) < 10:
# 3, 7, 11
list1.append(next(t))
print(list1)
list2 = [1, 8, 2, 4]
t1 = itertools.cycle(list2)
print(next(t1))
print(next(t1))
print(next(t1))
print(next(t1))
print(next(t1))
print(next(t... |
7e814127f1b60b8d78268dee7d9ed6f27457e70c | zerodayz/dailycoding | /Examples/Exceptions.py | 251 | 3.953125 | 4 |
name = "John"
age = 19
try:
print('Hello ' + str(name) + ', your age is ' + int(age))
except Exception as e:
print('Exception caught: %s' % e)
try:
raise NameError('HiThere')
except NameError:
print 'An exception flew by!'
raise |
a40506eaf66ec0af19289816a30e8ff2039e5868 | zerodayz/dailycoding | /Examples/Recursion.py | 350 | 4.1875 | 4 | def recursive(input):
print("recursive(%s)" %input)
if input <= 0:
print("returning 0 into output")
return input
else:
print("entering recursive(%s)" %( input -1 ))
output = recursive(input -1)
print("output = %s from recursive(%s)" %(output, input - 1))
retur... |
b8bc52fba483959f03cf4c33be6735fc1e1d5f47 | arpitsingh17/DataStructures | /find_substr.py | 269 | 3.953125 | 4 | # finding substring in a string
#substring = "sd"
#string = "asdfg"
def findstr(string1, substring1):
for i in range(len(string1) - len(substring1) + 1):
if (string1[i:i+len(substring1)] == substring1):
return i
print(findstr("asdfg","sd")) |
fd0494ab43d057e55d61d3a0b0c2797406da3e47 | arpitsingh17/DataStructures | /binarysearch.py | 697 | 4.125 | 4 | # Binary Search
# Input list must be sorted in this search method.
def bin(alist,item):
aalist = alist
midterm = alist[(len(alist)//2)]
found = False
while True:
try:
if item < midterm:
#print (alist[:((alist.index(midterm)))])
return(bin(alist[:((alist.index(midte... |
68bb058fda2c703036d8bd76c1c57171db1608a0 | ericwebsite/ericwebsite.github.io | /src/python/TheTemple(2).py | 1,376 | 4.125 | 4 | import random
print("Importable +")
import time
time.sleep(3)
print("You went in a temple. I dare you. ")
print(",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,")
time.sleep(3)
print("You saw...")
print("()()()()()()()()()()()()")
time.sleep(3)
power = input("Choose a power. waterBreathing(w),fireProtection(fp),Blas... |
1aa5bf7b3f6023f963ca41d83a91e49efd1c008d | ericwebsite/ericwebsite.github.io | /src/python/Color.py | 407 | 3.921875 | 4 | #Color? Rainbow? PYTHON!!!!!!?!?!?????
import turtle
#Import, turtle!!!!!!!!!!!!!!!
w = 1
t = turtle.Pen()
#t or turtle.Pen()?
t.speed(0)
#Go fast----------------------------------->!
turtle.bgcolor("black")
#bg means background
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
while True:
onscreencli... |
4a0a0f617cd498b694c0c5afa96d7f1999795604 | ericwebsite/ericwebsite.github.io | /src/python/Dir.py | 935 | 4.0625 | 4 | print("print,upper,lower,fformat,imporgt(,quit,or fix)")
a = True
b = False
while a :
f = input("choose1")
if f == "quit":
a == False
elif f == "print":
print("prints stuff out, see Adventure Game.")
elif f == "fformat" or f == "inporgt":
print('Try to choose "fix" next.')
el... |
ed1604fddb67a461eaa661d9eb310433d8d75c86 | ericwebsite/ericwebsite.github.io | /src/python/encoder-decoder.py | 405 | 3.734375 | 4 | s = int(input("Type a number to swap"))
c = input("encoding(e)or decoding(other)")
if c != "e":
s = 26-s
m = input("Type a message")
m = m.upper()
output=""
for letter in m:
if letter.isupper():
value = ord(letter) + s
letter = chr(value)
if not letter.isupper():
value -= 26
... |
e0547b6ee149d3cb35c3517593f044aee1b1ec2e | jarechalde/SDA-Project | /Main.py | 5,890 | 3.546875 | 4 | import urllib2
import urllib
import os
#First we get the file that contains all the urls for the files that we are going to use in this project
files = urllib2.urlopen('http://data.gdeltproject.org/gdeltv2/masterfilelist.txt')
web = files.read()
#Creating a file to save the urls
myfile = open("myfiles.txt","w")
myfi... |
e13775416dc65e96f2e30f0d2c5902562ebb679c | BenedictBen/alx-higher_level_programming | /0x01-python-if_else_loops_functions/102-magic_calculation.py | 130 | 3.796875 | 4 | #!/usr/bin/python3
def magic_calculation(a, b, c):
if a < b:
return c
elif c > b:
return a + b
else:
return a * b - c
|
03664714da4c72c21a93f6845e457baabe6616bd | TechnicalVishalJi/MegaProjects | /multiplayer_guessing_game.py | 1,358 | 4.03125 | 4 | import random
print("Guess Game\n")
p1 = input ("Player 1 enter your name.\n")
p2 = input ("Player 2 enter your name.\n")
list = []
def main(player , player2):
tchances = int(input("Enter number of chances\n"))
global list
chances = tchances
a = int(input(f"{player} - Enter first number\n"))
b = int(input(f"... |
109e1b80cf16892d04d34f7eb7d7d25fd407ae6a | rretiwala/Random-Code | /creditcard-1.py | 1,870 | 3.78125 | 4 | # File: CreditCard.py
# Description: Finds type and validity of credit card
# Student Name: Raza Retiwala
# Student UT EID: mrr2975
# Course Name: CS 303E
# Unique Number: 51200
# Date Created: 11/17
# Date Last Modified: 11/17
def is_valid(cc_num):
cc_num = str(cc_num)
new_numbe... |
d5b0e6cae118c886d8ac206b3af3e16ca0b4edf5 | j-thepac/Python_snippets | /SmallHighPow/smallhighpow.py | 896 | 4.21875 | 4 | """
We have the number 12385. We want to know the value of the closest cube but higher than 12385. The answer will be 13824.
Now, another case. We have the number 1245678. We want to know the 5th power, closest and higher than that number. The value will be 1419857.
We need a function find_next_power ( findNextPower ... |
08f2d5e5f13dcb98a8e419568b391b56439ae6cf | j-thepac/Python_snippets | /IntSeq/python/intseq.py | 1,626 | 4.21875 | 4 | """
Description:
Complete function findSequences. It accepts a positive integer n. Your task is to find such integer sequences:
Continuous positive integer and their sum value equals to n
For example, n = 15
valid integer sequences:
[1,2,3,4,5] (1+2+3+4+5==15)
[4,5,6] (4+5+6==15)
[7,8] (7+8==1... |
9e2720425cecb690c4351bcdb0bdebc83d6297a3 | j-thepac/Python_snippets | /CompleteSeries.py | 1,015 | 3.890625 | 4 | """
You are given an array of non-negative integers, your task is to complete the series from 0 to the highest number in the array.
If the numbers in the sequence provided are not in order you should order them, but if a value repeats, then you must return a sequence with only one item, and the value of that item mus... |
a8392bb255f782e8df7a3f3de74b6de227208404 | j-thepac/Python_snippets | /NotSecure/notsecure.py | 851 | 4.0625 | 4 | """
n this example you have to validate if a user input string is alphanumeric. The given string is not nil/null/NULL/None, so you don't have to check that.
The string has the following conditions to be alphanumeric:
At least one character ("" is not valid)
Allowed characters are uppercase / lowercase latin letters a... |
00d04451f85bab22ba848711f5c3352d1e088245 | j-thepac/Python_snippets | /calc/calc.py | 941 | 4.03125 | 4 | """
You have to create a function calcType, which receives 3 arguments: 2 numbers, and the result of an unknown operation performed on them (also a number).
Based on those 3 values you have to return a string, that describes which operation was used to get the given result.
The possible return strings are: "addition"... |
6b04d40c5c027e9e23ad40f03157733ec75c0a1e | j-thepac/Python_snippets | /Matchpatter/matchpattern.py | 673 | 3.765625 | 4 | """
Example of use:
predicate = find_matched_by_pattern('acs')
predicate('access') # True
predicate('sacrifice') # False
Examples of inputs/outputs:
Pattern: Word: Match:
acs access true
ascces false
scares false
vvl veturvel true
velivel false
bmb bom... |
79cabc1f0fe97e786db26ebd9caeee47088b7702 | j-thepac/Python_snippets | /RevAdd/revadd.py | 413 | 3.515625 | 4 |
class Solution:
def addTwoNumbers(self, l1, l2) -> list:
s1="".join(str(i) for i in l1)
s2="".join(str(i) for i in l2)
res= int(s1)+int(s2)
return [int(i) for i in (str(res))][::-1]
s=Solution()
l1 = [2,4,3]
l2 = [5,6,4]
assert (s.addTwoNumbers(l1,l2)==[7,0,8])
print("don... |
77ada479550021b32a348c179dc26253f3569134 | j-thepac/Python_snippets | /Overlap/overlap.py | 453 | 3.8125 | 4 | def merge_strings(first, second):
for i in range(0,len(first)):
if(first[i:] in second[0:len(first[i:])]):
return (first[0:i]+second)
return first+second
assert(merge_strings("abcde" ,"cdefgh" )== "abcdefgh")
assert(merge_strings("abaab" , "aabab" )== "abaabab")
assert(merge_strings("abc" ... |
7ca1c347acf873f665bdc1c358e01d68716f48b9 | j-thepac/Python_snippets | /Consecutive/consecutive.py | 1,192 | 4.0625 | 4 | """
In this Kata, we will check if a string contains consecutive letters as they appear in the English alphabet and if each letter occurs only once.
Rules are: (1) the letters are adjacent in the English alphabet, and (2) each letter occurs only once.
For example:
solve("abc") = True, because it contains a,b,c
solve... |
686a85218395e40eb72af068ae088946278602e2 | j-thepac/Python_snippets | /GCD/gcd.py | 524 | 4 | 4 | """
Find the greatest common divisor of two positive integers. The integers can be large, so you need to find a clever solution.
The inputs x and y are always greater or equal to 1, so the greatest common divisor will always be an integer that is also greater or equal to 1.
"""
def mygcd(x, y):
if (x==1 and y==1):... |
dd2381611d76916df71b010cbc62ed57fc8b1c9d | j-thepac/Python_snippets | /CountDigit/countdigit.py | 1,037 | 4.0625 | 4 | """
Take an integer n (n >= 0) and a digit d (0 <= d <= 9) as an integer.
Square all numbers k (0 <= k <= n) between 0 and n.
Count the numbers of digits d used in the writing of all the k**2.
Call nb_dig (or nbDig or ...) the function taking n and d as parameters and returning this count.
Examples:
n = 10, d = 1
... |
c7dfc6b9bbf3f103a6c4a127119edc8f0e0df1bd | j-thepac/Python_snippets | /Brackets/brackets.py | 1,423 | 4.21875 | 4 | """
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.
Every close bracket has a corresponding open bracket ... |
76fab9f98d60f01937e9947837e6c1e2c75e213a | j-thepac/Python_snippets | /Oddbit.py | 480 | 4.03125 | 4 | """
Return 1 when ANY odd bit of x equals 1; 0 otherwise.
x is unsigned.
(Assume "0 index", aka the least significant bit is considered position 0)
Assume x is 32 bits.
Example:
any_odd(2) will return 1 because at least one odd bit is 1 (0010).
ff
"""
def any_odd(x):
binary="{:032b}".format(x)
return 1 if "... |
ebf04b862009e61e6993d8216c0ffdb3db6cf5a2 | j-thepac/Python_snippets | /SameCase/samecase.py | 1,069 | 4.1875 | 4 | """
Write a function that will check if two given characters are the same case.
'a' and 'g' returns 1
'A' and 'C' returns 1
'b' and 'G' returns 0
'B' and 'g' returns 0
'0' and '?' returns -1
If any of characters is not a letter, return -1.
If both characters are the same case, return 1.
If both characters are l... |
14c7bf781e52c8f4eaa62b0d30dab3939d452180 | j-thepac/Python_snippets | /Phoneno/phoneno.py | 1,032 | 4.21875 | 4 | """
Write a function that accepts an array of 10 integers (between 0 and 9)== that returns a string of those numbers in the form of a phone number.
Example
create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) # => returns "(123) 456-7890"
The returned format must be correct in order to complete this challenge.
Don't fo... |
c8775eacdaca76a665f36f65761d9af051839c75 | leonparte/Python-Crash-Course-Learning-Projects | /Chapter 3/Test_3.2.3.py | 1,725 | 3.515625 | 4 | # 从列表中删除元素
players = ['Chalmers', 'Wade', 'James', 'Battier', 'Bosh', 'Allen']
# 使用del语句删除元素
print("\n-----------------------------------------\n")
del players[-1]
print(' The starting lineup of Miami Heat are:\n', players)
# 使用方法pop()删除元素
print("\n-----------------------------------------\n")
players... |
523293064f757ce22b3e4949905120fe6ce61bd9 | leonparte/Python-Crash-Course-Learning-Projects | /Chapter 3/Test_3.2.1.py | 403 | 3.53125 | 4 | # 修改列表元素
players = ['Wade', 'James', 'Bosh', 'Allen', 'Battier']
print("\n-----------------------------------------\n")
# 输出原始列表:
print("迈阿密终结比赛的阵容为:", players)
# 修改列表元素:
players[3] = 'Chalmers'
# 输出修改后的列表:
print("迈阿密的首发为:", players)
print("\n-----------------------------------------\n") |
2c332604bd9fa06c4e3594a5669b61b0a8f55b0e | leonparte/Python-Crash-Course-Learning-Projects | /Chapter 9/player.py | 1,209 | 3.9375 | 4 | # 使用类和实例
class Player():
"""描述一名篮球运动员"""
def __init__(self, name, age, team, positoin):
"""初始化描述运动员的属性"""
self.name = name
self.age = age
self.team = team
self.positon = positoin
self.year = 0
self.score = 0
def get_description(self):
... |
b8cfff5ac4b473edfbe2905e23c0fda96093cedc | Ko-jongyoon/ssmc_python | /basic/p15.py | 1,586 | 3.90625 | 4 | # PersonEx 클래스를 구성하시오
# 속성으로 name, age가 존재한다
# 액션(함수)로 getName, getAge 가 존재한다
# name과 age는 생성자에서 초기화 된다
########################################
# 파이썬의 모든 클래스의 슈퍼 클래스(근본 클래스)는
# Object 존재함
class PersonEx:
# 멤버변수
name = None
age = None
# 생성자
def __init__( self, name, age ):
self.name = name
... |
8310506b4e0c60e112268292f5bd2743c610b3e5 | Ko-jongyoon/ssmc_python | /basic/p5.py | 2,404 | 4 | 4 | '''
2. 여러개 데이터 (연속 데이터, 시퀀스 데이터)
- 리스트 :
[],
순서가 존재,
인덱스 존재(0,1,2~..),
값의중복허용
'''
# None : 값이 없다
nums = None
# 리스트 생성
nums = []
print( nums, type(nums), len(nums))
# 리스트 객체 생성
# 동적으로 생성되는방식이며, 반복작업시 안정적이다
nums =list()
print( nums, type(nums), len(nums))
# 10이하 양의 정수들의 리스트 생성
nums = [1,3,5,7,9]
print( nums, type(nums... |
f8ca792bbb5673e056a0b72ad6b0f8aa8fcef8e9 | Ko-jongyoon/ssmc_python | /basic/p10.py | 1,009 | 3.78125 | 4 | # 조건문
'''
조건이 1개
if 조건식:
수행코드
조건이 2개
if 조건식:
수행코드
else:
수행코드
조건(케이스) > 2
if 조건식:
수행코드
elif 조건식:
수행코드
else:
수행코드
'''
print('커피값을 지불해 주세요')
# input() : 콘솔에서 사용자 입력을 받는 함수
# 입력을 하고 엔터키를 칠때까지 블럭 대기 한다
# 사용자가 입력하고 엔터치면 입력값을 리턴한다.
# 리턴한 값의 타입은?
# 문자열 => 정수로 int()
money = int( input() )
# 1000원보... |
92893c7d0cbd15fbb4f43f9461ebcbd5cd56f0c6 | DiegoBMP/aprendiendo-python | /datatype.py | 489 | 3.5625 | 4 | # Strings
print("hola")
print('sdsdas')
print('''que pasa puta''')
print("""queres que te la ponga""")
print(type("hello wolrd"))
# Numbers
# Integer
print(30) #int
# Float
print(30.5) #float
# Boolean
True #bool
False
# List
[10, 20, 30, 55]
['hola', 'bye','queres', 'ahre']
[10, "hello", True, 1... |
bc1b5cc4df45da7c92e98c5156dde37cc19e382c | kazuoshi/python_sample | /CSVWriteRead_sample.py | 909 | 3.90625 | 4 | import tkinter as tk
import csv
def csv_writer():
csv_file = open('./python.csv', 'w', newline='')
writer = csv.writer(csv_file)
row = ('python', '-', 'izm', '1')
writer.writerow(row)
rows = []
rows.append(('python', '-', 'izm', '2'))
rows.append(('python', '-', 'izm', '3'))
r... |
e362ff3a5d949f03cceb6f8de2602b06d1d2cac4 | barthelemyleveque/Piscine_Python | /D00/ex06/recipe.py | 2,559 | 4.125 | 4 | import sys
import time
cookbook= {
'sandwich': {
'ingredients':['ham', 'bread', 'cheese', 'tomatoes'],
'meal':'lunch',
'prep_time':10,
},
'cake' : {
'ingredients':['flour', 'sugar', 'eggs'],
'meal':'dessert',
'prep_time':60
},
'salad':{
'ingre... |
b6f1ea768784718f0861ceeed23d999305a8e9bf | barthelemyleveque/Piscine_Python | /D00/ex09/guess.py | 951 | 4 | 4 | import random
import sys
print("This is an interactive guessing game!\nYou have to enter a number between 1 and 99 to find out the secret number.\nType 'exit' to end the game.\nGood luck!\n")
i = random.randint(1, 99)
user_input = 0
count = 0
while (user_input != i):
count += 1
user_input = input("What's your ... |
db397822bc94694d0e915df2346175020eba56e3 | barthelemyleveque/Piscine_Python | /D00/ex04/operations.py | 760 | 4 | 4 | import sys
if (len(sys.argv) != 3):
sys.exit("Usage: python operations.py <number1> <number2> \nExample: python operations.py 10 3")
num1 = sys.argv[1]
num2 = sys.argv[2]
if (num1.lstrip('-').isdigit() == 0 or num2.lstrip('-').isdigit() == 0):
sys.exit("Usage: python operations.py <number1> <number2> \nExampl... |
46bf0131d32983a2beb609a186f15ed1c9946f04 | barthelemyleveque/Piscine_Python | /D01/ex02/vector.py | 1,845 | 3.625 | 4 | import sys
class Vector:
def __init__(self, values, len_v=None):
if (isinstance(values, int) and values == 0):
if (isinstance(len_v, int) and len_v > 0):
i = 0
values = [None] * len_v
for x in range(0, len_v):
values[i] = float... |
58d7328768ff512c4c3fba77b58c0d51c14e19ba | aashirbad/Python | /EvenOdd.py | 160 | 4.15625 | 4 | num = (int)(input('Eneter a number : '))
if num % 2 == 0 :
print('The number',num,' is Even')
else:print('The number is Odd . \nplease add or sub 1 .')
|
e3d0453ecc100a5dd7d2bd72288b841976e92a06 | kjbala/PY4E | /as_08_2.py | 336 | 3.84375 | 4 | #Picking out the mail ID's
fname = input("Enter file name: ")
fh = open(fname)
count=0
for line in fh:
line=line.strip()
if not line.startswith("From:"):
continue
listline=line.split()
count=count+1
print(listline[1])
print('There were',count,'lines in the file with From as the ... |
0496ead53776f01db59c4a266e1431f5f0f6ba03 | kjbala/PY4E | /as_08_1_Learning.py | 347 | 3.703125 | 4 |
#Using dictonary to remove duplicates, File name romeo.txt
file=input("Enter the File Name: ")
fh=open(file)
lst=list()
fullword=list()
for line in fh:
line=line.rstrip()
word=line.split()
fullword=fullword+word
print(fullword)
fullword=list(dict.fromkeys(fullword))
fullword.sort()
print(ful... |
aeaae0098c9610660f53d33b870ab93b65b3252f | EyalHaim/N-Queens-Problem | /N-Queens-Problem.py | 4,171 | 3.90625 | 4 | ##############Version 1 of the problem###########################
#Given a chess board of size N*N containing only dragons, returns how many
#legal ways exist to locate N queens on the board
def queens_dragons(board):
return queens_dragons_rec(len(board), 0, 0, board)
def queens_dragons_rec(remaining, row, col, ... |
24e2383ff524701d646480e9fc15c147ee4ae9ab | MaximeThm/Automation_tasks | /removes_spaces_in_file_names.py | 343 | 3.640625 | 4 | import os
from tkinter.filedialog import askdirectory
#ask user to select directory
path = askdirectory()
for root, dirs, files in os.walk(path):
for f in files:
r = f.replace(" ", "")
f = os.path.join(root, f)
r = os.path.join(root, r)
if (r != f):
... |
f8dd6317c83061ec0bf5548e09570614fab7de7b | vladimirov/python-tutorial | /all/largest_number.py | 197 | 4.03125 | 4 | numbers = [3, 6, 24, 8, 4, 10]
first_number = numbers[0]
max_number = first_number
for each_number in numbers:
if each_number > max_number:
max_number = each_number
print(max_number)
|
c27282a67ea385dc1fbfa60e28803d4d9e5794a3 | GirishGore/Machine-Learning-Using-Python | /Unsupervised Learning/KMeans_Clustering.py | 1,821 | 3.65625 | 4 |
## Starting with python
from sklearn import datasets
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.cluster import KMeans
iris = datasets.load_iris()
print (iris.target_names)
print (type(iris))
wcss = []
for i in range(1, 15):
kmeans = KMeans(n_clusters = i, init = 'k-mean... |
f75b729a56ccdde3e161adc2ebfb6ae34069cc08 | anand13sethi/Data-Structures-with-Python | /Stacks/ReverseStack.py | 255 | 3.90625 | 4 | # Code to reverse elements of a stack by using only stack operations push() nad pop().
from StackDynamic import Stack
def reverse_stack(stk):
new_stack = Stack()
while not stk.is_empty():
new_stack.push(stk.pop())
return new_stack
|
ce499afe3bf4323bc35f81eda9cb02bbeb866f2b | anand13sethi/Data-Structures-with-Python | /Queue/QueueReverse.py | 963 | 4.15625 | 4 | # Reversing a Queue implemented using singly link list using stack.
from QueueUsingLinkList import Queue
class Stack:
def __init__(self):
self.stack = []
self.size = 0
def is_empty(self):
return self.size <= 0
def push(self, data):
self.stack.append(data)
self.s... |
189c3eb6a960a17c6cfca4f27354a21fc12a5728 | anand13sethi/Data-Structures-with-Python | /Stacks/StackDynamicArray.py | 1,036 | 3.953125 | 4 | # Stack implementation using array with repeated doubling.
# Optimal approach than iterative.
class Stack:
def __init__(self, limit=10):
self.stklist = []
self.limit = limit
self.length = -1
def push(self, data):
if self.length >= self.limit - 1:
self.resize()
... |
10e9c580ad705977df03aa37e7e1839caefc63fd | anand13sethi/Data-Structures-with-Python | /Linked List/DoublyLinkedListNode.py | 5,021 | 4.09375 | 4 | # Doubly Link List implementation, with Floyd's Cycle Detection algorithm.
class Node:
def __init__(self, data=None, next=None, prev=None):
self.data = data
self.next = next
self.prev = prev
self.head = None
self.tail = None
self.length = 0
def set_... |
f745a42b0a35b8366082bae1208dde293ffcb99e | besigne/scrapper | /model/car.py | 326 | 3.59375 | 4 | class Car:
def __init__(self, name, price, fuel):
self.__name = name
self.__fuel = fuel
self.__price = price
@property
def name(self):
return self.__name
@property
def fuel(self):
return self.__fuel
@property
def price(self):
return self.__... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.