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 |
|---|---|---|---|---|---|---|
994921ed41e8a38a306e9b76bd14fe3fcce122d1 | islndr1/python | /lab2.py | 999 | 4.0625 | 4 | alphabet = 'abcdefghijklmnopqrstuvwxyz,.!?;:_- ABCDEFGHIJKLMNOPQRSTUVWXYZабвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ'
menu = True
while menu :
print("Меню: ")
print("1: Шифровать")
print("2: Раскодировать")
print("3: Выход")
pick = int(inp... |
7908203039fd811602f482efc1a9153a39d855f7 | Mjk29/CS_100_H03 | /Python Files/9_14_16/MattKehoe_HW01.py | 1,026 | 4.1875 | 4 | flowers= ['rose', 'bougainvillea','yucca', 'marigold', 'daylilly', 'lilly of the valley']
print ('potato' in flowers)
thorny = flowers[:3]
poisonous = flowers[-1]
dangerous = thorny + poisonous
print (dangerous)
print (poisonous)
print ( thorny)
print ( flowers)
xpoint = [0,10,6,7]
ypoint = [0,10,6,8]
radiu... |
c6fae76df7f6a45f542ab3109b80ced6308157ac | Stefs-2142/learn-homework-1 | /5_while2.py | 1,309 | 3.59375 | 4 | """
Домашнее задание №1
Цикл while: ask_user со словарём
* Создайте словарь типа "вопрос": "ответ", например:
{"Как дела": "Хорошо!", "Что делаешь?": "Программирую"} и так далее
* Напишите функцию ask_user_dict() которая с помощью input() просит
пользователя ввести вопрос, а затем, если вопрос есть в словаре, ... |
a1c808455c90033428a212fd2ddc45ecc50f539f | RaspberryPIApps/Brittany-and-Roger | /Robot GUI v2.py | 2,625 | 3.859375 | 4 |
# coding: utf-8
## Robot GUI
###### Please select Cell > Run All !! DO NOT close turtle world before GUI.
# In[9]:
from swampy.TurtleWorld import *
from math import *
import random
from Tkinter import *
import tkFont
import turtle
# In[10]:
#Find the comma and parse the string that follows
def Parse():
inpu... |
e5f6d395c606ef5ef59fb9167b790c4df7acb70a | KshitijShah-GitHub/PythonSQLite3Test | /database_program.py | 16,997 | 4.0625 | 4 | import sqlite3
import tkinter as tk
from tkinter import ttk
# Sanitize input at some point because xkcd comic num 327
# View doesn't correctly refresh after deletion. Still deletes from table
def setup_table(conn):
"""
(Connection) -> Cursor
Main database management
"""
table_name = "S... |
89259cf5e708cda2eea7515198170fc85d777f1a | liuw/project-euler | /p21.py | 2,114 | 3.625 | 4 | #!/usr/bin/python
import math
##import itertools
##
### fast prime generator taken from Alex and others
##def erat2():
## D = {}
## yield 2
## for q in itertools.islice(itertools.count(3), 0, None, 2):
## p = D.pop(q, None)
## if p is None:
## D[q*q] = q
## yield q
## ... |
0af1a0a35eef6716366747cd20e800046e2c7305 | liuw/project-euler | /p33.py | 1,515 | 3.671875 | 4 | #!/usr/bin/python
def solve():
numerator = 1
denominator = 1
# xz / zy ; zx / yz ; xz / yz ; zx / zy
# z being the number to be removed
# So that x, y and z cannot be 0
for x in range(1, 10):
for y in range(1, 10):
for z in range(1, 10):
c = float(x) / floa... |
8804d6c08269a6939b6739d5bd6821e937735b33 | asimonia/datastructures-algorithms | /Recursion/listsum.py | 428 | 4.1875 | 4 | """
A recursive algorithm must have a base case.
A recursive algorithm must change its state and move toward the base case.
A recursive algorithm must call itself, recursively.
"""
def listsum(numList):
theSum = 0
for i in numList:
theSum = theSum + i
return theSum
def listsum2(numList):
"""Recurisve version of... |
55e1575a7e4bb02c5f1b55073cca5bdc3d58b3a1 | mukeshsinghmanral/Python-part-2 | /py/armstrong.py | 220 | 4.03125 | 4 | n=int(input("enter any positive number: "))
sum=0
x=n
m=0
while x>0:
m=x%10
sum=sum+(m*m*m)
x=x//10
if sum==n:
print(n,"is armstrong number")
else :
print(n,"is not armstrong number")
|
2d2d40ad0d0e97894f8cdec6bef72a46a5544c14 | mukeshsinghmanral/Python-part-2 | /py/fib.py | 456 | 4.3125 | 4 | def fib(n):
''' this is to find fibonacci series upto some limit'''
a,b=0,1
print("fibonacii series of",n,"terms is :",end=' ')
print(a ,b ,end=' ')
for i in range(n-2):
c=a+b
print(c,end=' ')
a=b
b=c
try:
n=int(input('enter number of terms: '))
if n==1:
print(0)
elif n<=0... |
05c3b986cc55e8fefa350e7fca79f346f061880e | mukeshsinghmanral/Python-part-2 | /py/methodoverriding.py | 378 | 3.59375 | 4 | class Company:
def __init__(self,no_emp,sal,exp):
self.no_emp=no_emp
self.sal=sal
self.exp=exp
def __add__(self, other):
total_emp=self.no_emp+other.no_emp
total_sal=self.sal+other.sal
total_exp=self.exp+other.exp
e3=Company(total_emp,total_sal,total_exp)
print(e3.no_emp,e3.sal,e3.exp)
e1=C... |
fb324daf2c0f56a5492cf644dab7e5493f3a6584 | mukeshsinghmanral/Python-part-2 | /py/decoratersd.py | 181 | 3.6875 | 4 | def sub(a,b):
print(a-b)
def decor(func):
def swap(x,y):
if x<y:
x,y=y,x
return func(x,y)
return swap
sub1=decor(sub)
sub1(23,423) #calling inner as sub1=inner |
bddac420b6f84d431efc615e6bf9b59a9b2c4db7 | mikekhalil/LeetCode | /LongestPalindrome.py | 566 | 3.765625 | 4 | #naive solution - find a better one (TLE)
class Solution(object):
def isPalindrome(self,string):
return string == string[::-1]
def longestPalindrome(self, string):
#find the longest palindrome within a string
i, j, pal = 0, 0, string[0]
while i < len(string):
j = i +... |
7adecd748f4722a775d9f3de15b74ff429f2bd66 | mikekhalil/LeetCode | /SlidingAverage.py | 633 | 4.09375 | 4 | '''
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
For example,
MovingAverage m = new MovingAverage(3);
m.next(1) = 1
m.next(10) = (1 + 10) / 2
m.next(3) = (1 + 10 + 3) / 3
m.next(5) = (10 + 3 + 5) / 3
'''
class MovingAverage(object):
def __init__(... |
112c64b9c701a1c8657b0af10c70d3e0cd7f4918 | mikekhalil/LeetCode | /ReverseWords.py | 457 | 3.890625 | 4 | class Solution:
def reverseWords(self, s):
sentence = s.split()[::-1]
reversedString = ""
for word in sentence:
reversedString += word + " "
if len(reversedString) > 0:
reversedString = reversedString[:-1]
print reversedString
... |
4efee74176c8c1709fcda8f3708c8d4457374078 | daliborkruljac/CompletePythonCourseTraining | /utils/common/file_operations.py | 218 | 3.53125 | 4 | def save_to_file(userstring, filename):
with open(filename,'w') as file:
file.write(userstring)
def read_to_file(filename):
with open(filename, 'r') as file:
return file.read().split('\n')
|
4a192d690be89ad71edba3b53e28d952e5301cd8 | daliborkruljac/CompletePythonCourseTraining | /15_csv_to_json.py | 701 | 3.921875 | 4 | # Please read the instructions carefully and write your script here:
# You need to:
# - read data from csv_file.txt
# - process data and convert them into a single JSON object
# - store the JSON object into json_file.txt
# Your code starts here:
# Output should look like:
# [{"club": "Manchester United", "country": "... |
4e370638825e55495e91e49cf204db9ab6f07709 | Setsaa/Python-key-generator | /Codegenerator.py | 1,189 | 3.875 | 4 | import string
import random
keys = 'keys.txt'
def key_generator(size=15, n_keys=1, chars=string.ascii_uppercase + string.digits):
"""
Generates a unique key that can be used to identify a purchase.
"""
key = ''.join(random.choice(chars) for x in range(size))
with open('keys.txt', 'a') as output_fi... |
8f4ab4449ce704177aa6ac02f553ea1840468074 | traveling-soul/python | /design_pattern/strategy_pattern_v1.py | 1,517 | 3.5625 | 4 | import math
class CashSuper:
"""现金收费抽象类"""
def accept_cash(self, money):
pass
class CashNormal(CashSuper):
"""正常收费子类"""
def accept_cash(self, money):
return money
class CashRebate(CashSuper):
"""打折收费子类"""
def __init__(self, money_rebate):
self.mone... |
0581910cdbbe08ebd1a0abc72e97d87e26d81136 | traveling-soul/python | /design_pattern/test/single_test.py | 293 | 3.765625 | 4 | class Singleton:
_instance = None
def __new__(cls):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(cls)
return cls._instance
class MyClass(Singleton):
a = 1
obj = MyClass()
obj2 = MyClass()
print(obj is obj2)
|
fee88f2ea3fac741c8fdb8c58c40cc52940c9294 | traveling-soul/python | /design_pattern/test/singleton.py | 956 | 3.515625 | 4 | # import threading
#
# class SingletonType(type):
# _instance_lock = threading.Lock()
# def __call__(cls, *args, **kwargs):
# if not hasattr(cls, "_instance"):
# with SingletonType._instance_lock:
# if not hasattr(cls, "_instance"):
# cls._instance... |
c79ad1517ca4a83f4945c13e188d2c857e7b7903 | traveling-soul/python | /algorithm/递归阶乘.py | 429 | 3.84375 | 4 | # def factorial(n):
# if n == 1:
# return 1
# return n * factorial(n - 1)
# print(factorial(1000))
# 优化,尾递归--当递归调用是函数体中最后执行的语句并且它的返回值不属于表达式一部分时, 这个递归就是尾递归。
def factorial2(n, result):
if n == 1:
return result
return factorial2(n - 1, n * result)
print(factorial2(1000... |
81be9822eeb278b76f47998f7bc7897814b73d97 | traveling-soul/python | /design_pattern/test/class_item.py | 584 | 3.765625 | 4 | # class testsetandget:
# kk = {}
#
# def __getitem__(self, key):
# return self.kk[key]
#
# def __setitem__(self, key, value):
# self.kk[key] = value
#
# a = testsetandget()
# a['first'] = 1
# print(a['first'])
#
# a.__setitem__('second', 2)
# print(a.__getitem__('second'))
... |
8cf3fadbdbbf918606ef21f70229e8b8f9e5ab70 | drjod/coderesourcesandwastereservoir | /pyMunich2016/tdd/code/fibonacci.py | 180 | 3.8125 | 4 | def fib(number):
if number < 0:
raise ValueError
if number == 0:
return 1
if number == 1:
return 1
return fib(number-2) + fib(number-1)
|
94946f2b13337387fcbfc60769930e0e4ba7e0c0 | rahulk-gh/PythonPractice | /cool problems/noCondorLoop.py | 268 | 3.53125 | 4 | # take 3 inputs, x, hi and lo. When outside the hi and lo give back hi if above hi and lo if below low. if within the range give back x . DO NOT USE CONDITIONALS
x = 3
hi = 10
lo = 1
def clip ( lo, x, hi):
return ( min (max(x, lo) , hi))
clip ( lo, x, hi )
|
48183700c36408bfe44b2bb3263c4eae2b014de4 | dlimla/Algorithms | /recipe_batches/recipe_batches.py | 1,369 | 3.875 | 4 | #!/usr/bin/python
import math
recipe = { 'milk': 100, 'butter': 50, 'flour': 5 }
ingredients = { 'milk': 132, 'butter': 48, 'flour': 51 }
def recipe_batches(recipe, ingredients):
# pass
# print(len(recipe))
# print(len(ingredients))
num_of_times = 0
can_still_bake = True
if len(recipe) > len(ingredient... |
e2271c02164394cf0eb9d397df64029f76931f22 | JoKerDii/ProbSol-with-Algor-dataStr-Using-Py | /recursion/listsum.py | 399 | 4 | 4 | """Calculating the Sum of a List of Numbers
normal function and recursive function"""
def listsum(numList):
theSum = 0
for i in numList:
theSum = theSum + i
return theSum
print(listsum([1,3,5,7,9]))
def recursionListsum(numList):
if len(numList) == 1:
return numList[0]
else:
... |
f4a7e9c5f8d758acae98bcfa40eee9d4f8d4f858 | rockneurotiko/grupo-python | /Semana 3/Sem3EjLib1.py | 199 | 3.6875 | 4 | def repite_hola(n):
"""
Recibe un numero "n" y escibe "Hola" n veces
>>> repite_hola(3)
Hola
Hola
Hola
"""
for i in range(n):
print("Hola")
repite_hola(3)
repite_hola(5)
repite_hola(10) |
a0a8a8a9065efb58af3bd88b0f07614f2da72b6f | David-Simonetti-ND/Covid-Spread-Visualizations | /covid.py | 9,790 | 4 | 4 | import csv
import plotly.express as px
import pandas as pd
import poparea
# general overview of how the program works: Read in number of covid cases and covid deaths from CSV files downloaded onto local machine.
# then also read in ISO 3 country codes from a seperate CSV file. Also use requests to access CIA world fact... |
e5ff7e75fb480a58714ad69e68b1684a68808ddd | savelievayuliia/small-py-programs | /task16_program.py | 1,073 | 4.09375 | 4 | def marks():
mark1 = float(input("Enter your 1st mark: "))
mark2 = float(input("Enter your 2nd mark: "))
mark3 = float(input("Enter your 3d mark: "))
mark4 = float(input("Enter your 4th mark: "))
mark5 = float(input("Enter your 5th mark: "))
return mark1, mark2, mark3, mark4, mark5
ma... |
99af30d15b01bdaeed7a3c45da1a2014d65618e1 | csudcy/adventofcode | /2016/16.py | 1,161 | 3.8125 | 4 |
def extend(data):
return data + '0' + ''.join(
(
'0' if d == '1' else '1'
for d in data[::-1]
)
)
assert extend('1') == '100'
assert extend('0') == '001'
assert extend('11111') == '11111000000'
assert extend('111100001010') == '1111000010100101011110000'
def extend_un... |
8b7cb759570e9e573ea9c098a739ffe4c9f91ebf | matimartin/Full-Stack-Web-Developer-Nanodegree | /P1-Project Movie Trailer Website/media.py | 967 | 3.703125 | 4 | import webbrowser
class Movie():
"""This class provides a way to store movie related information"""
# Al ser una variable global el nombre es en mayuscula
VALID_RATINGS = ["G", "PG", "PG-13", "R"]
# Estos son atributos, o datos de la clase Movie()
# A continuacion vemos un constructor, cuando se... |
8fd8b3172f29beb2f4530aaf3a31010fd0499815 | s-graham42/PythonOOP | /user_acct_assoc.py | 2,199 | 4.0625 | 4 | # ASSOCIATING BETWEEN CLASSES
# DEFINE USER CLASS
class User:
def __init__(self, username = 'unk', email_address = 'unk'):
self.user = username
self.email = email_address
self.account = BankAccount(0, 0.01)
def make_deposit(self, amount):
print(f"{self.u... |
32fa10ffcbd9f145572f6ca8a5dc47aa8108ae1a | Dinu977/Innomatics_Internship_APR_21 | /Task_2(Python Programming)/Task_2.py | 4,979 | 3.75 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
# Question 1
if __name__ == '__main__':
x = int(input())
y = int(input())
k = int(input())
n = int(input())
ans_lst=[]
for x1 in range(0,x+1):
for y1 in range(0,y+1):
for k1 in range(0,k+1):
s=x1+y1+k1
... |
149efab90f5dd53b8748dd617048882983b2fabf | noshah/Python_Practice | /AlienInvasion/new.py | 776 | 3.921875 | 4 | # HELPFUL FOR ALIEN INVASION.
import pygame
# First, create you group
gems = pygame.sprite.Group()
class Jewel (pygame.sprite.Sprite): # Inherit from the Sprite
def __init__ (self, *args): # Call the constructor with whatever arguments...
# This next part is key. You call the super constructor, and ... |
c319e7570b20e32da9e5f5d67d75a4d8562212c0 | noshah/Python_Practice | /downloading_data_chapter16/sitka_rainfalls.py | 913 | 3.5 | 4 | import csv
from datetime import datetime
import matplotlib.pyplot as plt
filename = 'data/sitka_weather_2018_simple.csv'
with open(filename) as f:
reader = csv.reader(f)
header = next(reader)
print(header)
rainfalls, dates = [], []
for row in reader:
current_dates = datetime.... |
001a690ce708e3e07437287fc8943368e731563f | xiao-do-do/SSMCodeGenerate | /src/utils/Utils.py | 2,863 | 3.53125 | 4 | import os
# 获取文件夹下所有的文件
from datetime import datetime
def file_name(file_dir):
L = []
for root, dirs, files in os.walk(file_dir):
for file in files:
if os.path.splitext(file)[1] == '.template': # 想要保存的文件格式
L.append(file)
return L
# 下划线转驼峰
def str2Hump(text):
if ... |
8df137c1bf7a5a3cd1c5009006b31f3af7b91fcf | Dinu28/Python3 | /Lesson9.py | 256 | 4.125 | 4 | #!/usr/bin/env python
#File operations
###################################
#Find a word in the file
fil=open("test1.txt","r")
buff=fil.read()
word=raw_input("Enter a word to search:")
if(word in buff):
print("Yes,Found it!")
else:
print("Not Found!")
|
9fb3b6fbeb126d535170fedbc71699f973f3ca5c | AleRiccardi/technical-neural-network-course | /exercise-03/programming_assignment/mlp.py | 8,339 | 3.703125 | 4 | import random
from abc import abstractmethod
import numpy as np
import matplotlib.pyplot as plt
T_TANH = 'tanh'
T_LOGISTIC = 'logistic'
T_IDENTITY = 'identity'
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def derivative(x, transfer=T_TANH):
if transfer == T_TANH:
return 1 - np.tanh(x) ** 2
elif... |
eb83554b9c70faa225bd526410a53405f5cc0790 | caboe2012/network_graphs | /App2_Project_NetworkReslience.py | 6,848 | 4.0625 | 4 | ''' Algorithmic_Thinking 1 - Module 2 '''
from collections import deque
import random
#popleft to remove and return leftmost element(the head of the queue)
#append to add new entry
GRAPH5 = {1: set([2, 4, 6, 8]),
2: set([1, 3, 5, 7]),
3: set([4, 6, 8]),
4: set([3, 5, 7]),
5: set... |
c8a4dbda658b550211919b6e07a9330b1acf222a | Squareroot7/Python | /LargestPalindromNum.py | 1,774 | 4.25 | 4 | #Largest palindrom number
#A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
#Find the largest palindrome made from the product of two 3-digit numbers.
#you have to find the LARGEST, so maybe you have to start from the biggest number... |
ec6184ade44125c17d25e6a21d60144febb66039 | Squareroot7/Python | /MessedUpRugby.py | 1,997 | 3.546875 | 4 | #trovare tutte le possibili permutazioni del numero di punti fatti da una squadra:
#conversions vale 7
#tries vale 3
#kicks vale 2
kicks=0
tries=0
conversions=0
CONVERSIONS=7
TRIES=3
KICKS=2
case=[]
case.append(KICKS)
case.append(TRIES)
case.append(CONVERSIONS)
def main():
numero=int(input('Qual è stato il... |
60d9c01e0a77737e920466936dbc715afbeb16ee | Squareroot7/Python | /P3.12.py | 1,187 | 3.859375 | 4 | #Programma conversione lettere in voto numerico e viceversa
Scelta=input('Convertitore Voto Numerico/Letterale o Letterale/Numerico inserisci N da numerico a letterale o L da letterale a numerico ')
#int(flag=0)
if Scelta== 'N':
votoNumerico=(input('Inserisci il voto numerico da convertire '))
if votoNumerico==... |
aaa29814e72d6140f9a8211b172f19a13a532bc1 | Squareroot7/Python | /SmallestMultiple.py | 1,863 | 4.03125 | 4 | #2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
#What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
divisor=20
def SmallestDivisible(divisor):
smallest=1
#Numeri primi
prime=[]
for i in range(di... |
15466f9d53f4ce6b97d578d0b26941b3e02f7c86 | purvi0116/SAT-solver | /disconnect-harness.py | 675 | 3.6875 | 4 | #!/usr/bin/python3
# sample harness; your code should work against this code without
# any modification in this code. For any issues in this code
# please report asap.
# your code lives in this file; we will import it
import disconnect
graph = [(2,5),(2,3),(3,4),(4,5), (3,5),(5,6),(3,6)]
s = 2
t = 6
# ~~~~ API CALL... |
646c3e8ab949621e0ff493db028491e3e8a6ae28 | FernandoCL1991/Leet_Code | /RomanToIntegerExc.py | 787 | 3.640625 | 4 | ## Leet Code, ex. 2: "Roman to Integer"
# Convert a roman numeral to an integer
class Solution(object):
def romanToInt(self, s):
dic = {
"I":1,
"V":5,
"X":10,
"L":50,
"C":100,
"D":500,
"M":1000,
... |
a3a1ad178869970c28497eb53e072823635897c4 | kiaph/SummerRe | /particle/tracker.py | 1,694 | 4.09375 | 4 | #Exercise 15, CH10, p. 337:
#Tracker class to display projectile motion
from graphics import *
from projectile import *
from random import randrange
import time
class Tracker:
def __init__(self, window, objToTrack):
#print("construct Tracker object.")
self.p = objToTrack
self.x = self.p.g... |
fffc9f5427e0bc5d91fa09b44a6c0e13ef77cf0c | somesh-paidlewar/Basic_Python_Program | /make_a_triangle.py | 673 | 4.5 | 4 | #To draw a Triangle with three points as input with mouse
from graphics import *
win = GraphWin('Make a Triangle',600,600)
win.setCoords(0.0,0.0,10.0,10.0)
message = Text(Point(5,0.5), 'Click any three points to draw a Triangle')
message.draw(win)
#Get and draw three vertices of the Triangle
p1 = win.getMouse()
p1.... |
2a134c9eb2849803e9b6265b619288a47511652f | kanika011/Python-Code-Questions | /IsomorphicStrings.py | 1,145 | 4.125 | 4 | #Isomorphic strings
#Given two strings s and t, determine if they are isomorphic.
#Two strings are isomorphic if the characters in s can be replaced to get t.
#All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same charact... |
95eba8abd76bc48afb8413a1f71dc486bd8cf1f8 | julissaf/Python-Code-Samples-1 | /W3P6 MPG for car.py | 221 | 3.734375 | 4 | #Julissa Franco
#03/14/2019
# Compute MPG for a a car
miles_driven = input("Enter miles driven:")
miles_driven = float(miles_driven)
gallons_used = input("Enter gallons used:")
gallons_used = float(gallons_used)
|
09f1e4eec04b7dc9df0012106ddce4c36381c623 | kangwonlee/nmisp | /10_root_finding/root_finding.py | 3,832 | 3.546875 | 4 | import math
import pylab as py
def sequential(f, x_init, x_interval, epsilon, x_final):
# result 의 초기값
# Initial value for sqrt_10
result = 'Not Found'
# 일련의 x_i 값을 미리 준비한다
# Prepare a series of x_i values in advance
x_array = py.arange(x_init, x_final+x_interval*0.5, x_interval)
# 몇번 반복... |
e0fe6d53441a8d1a5b91f65dc6dfbd2ee0dc7b40 | zaeval/boj-solving | /4673_self_num.py | 718 | 3.578125 | 4 | che = [x for x in range(1, 10001)]
def binarySearch(item):
first = 0
last = len(che) - 1
found = False
while first <= last and not found:
midpoint = (first + last) // 2
if che[midpoint] == item:
found = True
del che[midpoint]
else:
if item <... |
f62a9fa8e471bb0f92114ece5a31cf2ba2f97859 | atulsinha007/C-source-codes | /SILVER.py | 207 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 22 07:30:00 2016
@author: ok
"""
#silver
from math import log
while True:
n=int(input())
if n==0:
break
print(int(log(n,2))) |
fa392172f4530a320372d349e498cc8aeca273cb | ilray88/python_ShuJuWaJueShiJian | /章节2-数据挖掘/4_Pandas/013.py | 2,465 | 3.90625 | 4 | #使用Python数组创建
import pandas as pd
import numpy as np
# DataFrame 简单应用
data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'], 'year': [2000, 2001, 2002, 2001, 2002],
'pop': [1.5, 1.7, 3.6, 2.4, 2.9]}
frame = pd.DataFrame(data)
print(frame)
# 如果指定了列顺序,则DataFrame的列就会按照指定顺序进行排列。
print(pd.DataFrame(data, c... |
de0041abff5d3923c6a19c31661f90360984d045 | ilray88/python_ShuJuWaJueShiJian | /章节3-Python快速入门-完整版/code/re-test.py | 2,192 | 4 | 4 | #1)匹配查询函数
#代码1:展示了match函数的应用:
import re
print(re.match('www', 'www.baidu.com').span()) #在起始位置匹配
print(re.match('com', 'www.baidu.com')) #不在起始位置匹配
#代码2:展示了group()获取匹配对象。
import re
line = "Cats are smarter than dogs"
match= re.match( r'(.*) are (.*?) .*', line, re.M|re.I)
if match:
print "match.group() : ", matchO... |
c4865b9bd09c1887de4efc467501e689692edc5a | tartaponei/URI | /iniciante/1759hohoho.py | 101 | 3.71875 | 4 | n = int(input(""))
s = ""
for i in range(n):
s += "Ho "
print("{}{}" .format(s.rstrip(), "!"))
|
ceefd799fedfeb2703215f55681927b70ede0749 | tartaponei/URI | /iniciante/1131grenais.py | 705 | 3.671875 | 4 | r = 1
grenais, vitorias_inter, vitorias_gremio, empates = 0, 0, 0, 0
while(r == 1):
x = input("").split()
inter = int(x[0])
gremio = int(x[1])
if(inter > gremio):
vitorias_inter += 1
elif(inter < gremio):
vitorias_gremio += 1
else:
empates += 1
grenais += 1
pri... |
e8d501b02b2956d8fd3969d165672aae992e45aa | tartaponei/URI | /iniciante/1180posicaomenor.py | 286 | 3.59375 | 4 | #dá resposta errada não sei pq
n = int(input(""))
x = []
s = input("").split()
for i in range(n):
x.append(s[i])
menor = x[0]
posicao = 0
for i in range(n):
if(x[i] < menor):
menor = x[i]
posicao = i
print("Menor valor:", menor)
print("Posicao:", posicao)
|
93c16bf1adb763b1c3b6770154508266f2f95fef | tartaponei/URI | /iniciante/1847inverno.py | 407 | 3.515625 | 4 | s = input("").split()
a = int(s[0])
b = int(s[1])
c = int(s[2])
if(b < a):
if(c >= b):
cara = ':)'
elif(c < b and b-c < a-b):
cara = ':)'
else:
cara = ':('
elif(b > a):
if(c <= b):
cara = ':('
elif(c > b and c-b < b-a):
cara = ':('
else:
cara = ':... |
730247cb32a71e89664317e25207e5ef031dd32f | tartaponei/URI | /iniciante/1071somaimpares.py | 199 | 3.5625 | 4 | x = int(input(""))
y = int(input(""))
s = 0
if(x > y):
maior = x
menor = y
else:
menor = x
maior = y
for i in range(menor+1, maior):
if(i % 2 != 0):
s = s + i
print(s)
|
379a70d751799006ee4f04bc62776e4b8064cd79 | tartaponei/URI | /iniciante/1035selecao.py | 222 | 3.734375 | 4 | x = input("").split()
a = int(x[0])
b = int(x[1])
c = int(x[2])
d = int(x[3])
if(b > c and d > a and c + d > a + b and c > 0 and d > 0 and a % 2 == 0):
print("Valores aceitos")
else:
print("Valores nao aceitos")
|
a35ecd5b7f404548f5fc07755d80638995f84058 | JasJohn3/Machine_Learning_Classification | /Machine_Learning_Classification.py | 821 | 4.03125 | 4 | from sklearn import tree
import math
#classification of Circles vs Squares
#syntax for features
#Features =Has a radius, Has an Area
features = [[1,1*math.pi],[1 ,2*math.pi],[3 ,3*math.pi],[0,1*1],[0,2*2],[0,3*3]]
#Labeled Training Data
#labels = ["Sports-Car","Sports-Car","Minivan","Minivan"]
#0=Circle, 1=Square
lab... |
4f6f48bbe3f764c6daaac5dbd30e24bfe0d4a983 | AustenHsiao/CS199 | /Su_2019_Term_1/Homework/Tic_Tac_Toe.py | 2,700 | 4 | 4 | #Tic tac toe
#Austen Hsiao
#Assignment 4
def player_move(move_list):
x = int(input("Enter a position to take: ")) #What spot does the player want to take?
if x in move_list: #if it's a viable move
return x #return the value
else:
print("\nThis is an invalid move. Enter an open position.") #if its not a viable m... |
d547eb46385092ed08e9bbd10792f10557c6adb2 | AustenHsiao/CS199 | /Su_2019_Term_1/CS250/HW4_Q2.py | 185 | 4.0625 | 4 | #Fibonacci numbers with recursion
def r_fib(x):
if x == 0:
return 0
elif x == 1:
return 1
else:
return r_fib(x-1) + r_fib(x-2)
a = int(input("Enter n : "))
print(r_fib(a))
|
effcf4960a460ebd2958a96853c823b57e402662 | git04112019/Python-Crash-Course | /hello.py | 4,118 | 4.1875 | 4 |
# String Formatting & Methods
# Lists: ordered, changeable, allows duplicate members
# Create list
numbers = [1, 2, 3, 4, 5]
fruits = ['Apples', 'Oranges', 'Grapes', 'Pears']
# Use a constructor
# numbers2 = list((1, 2, 3, 4, 5))
# Get a value
print(fruits[1])
# Get len
print(len(fruits))
# Append to Lít
fruits.... |
16d8453057bec7f19a9a76788e9ff3ec2c331071 | fortunee/bc-python-xv | /exercises/even_numbers.py | 161 | 3.9375 | 4 | def even_numbers(low, bound):
for i in range(low, bound):
if i % 2 == 0:
return i
else:
print "probably not an even number"
print even_numbers(2, 10) |
46a3f4e086881c8f3a1ca3bbf5240de0ab1e11b1 | RobARC/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/0-square_matrix_simple.py | 134 | 3.640625 | 4 | #!/usr/bin/python3
def square_matrix_simple(matrix=[]):
square = [list(map(lambda x: x**2, i)) for i in matrix]
return square
|
813c89177d1d8656191b2a063254c0b69663d62c | RobARC/holbertonschool-higher_level_programming | /0x11-python-network_1/3-error_code.py | 550 | 3.671875 | 4 | #!/usr/bin/python3
""" script that takes in a URL, sends a request to the URL and displays
the body of the response (decoded in utf-8).
"""
from urllib import request
from urllib.error import HTTPError
from sys import argv
def main(argv):
""" method to get http errors """
url = argv[1]
try:
... |
29cbddfb99808be88694caf5dc45cc62a13be4af | RobARC/holbertonschool-higher_level_programming | /0x06-python-classes/100-singly_linked_list.py | 2,328 | 4.03125 | 4 | #!/usr/bin/python3
"""
Single Linked List module
Contains functions to create a basic singly linked list
"""
class Node:
"""
Define a Node of a single linked list
"""
def __init__(self, data, next_node=None):
"""
Method to initializate a Node object
"""
self.__data = ... |
b2fce549968e6dfcb39beaf39acbcc7ed0481a90 | somenbg/algorithm | /binary_search_recursive.py | 920 | 4.21875 | 4 | def binary_search_recursive(list_to_search: list, start_index: int, end_index: int, element_to_search: int):
'''
Usage:
list = [1,2,3,4,5,6]
binary_search_recursive(list, 0, len(list1)-1, 1)
Output:
"Element '1' is at index '0'"
'''
if start_index <=... |
50a1abf78776077cce0d0133767e3dd65bd90969 | somenbg/algorithm | /dijkstra_shortest_path.py | 2,775 | 3.765625 | 4 | class Node:
def __init__(self, data, indexLoc = None):
self.data = data
self.index = indexLoc
class Graph:
@classmethod
def create_from_node(self, nodes):
return Graph(len(nodes), len(nodes), nodes)
def __init__(self, row, column, nodes = None):
self.adj_mat = [[0]... |
a04544029812c5de47fae5985fe11dd425df1b45 | somenbg/algorithm | /trie_node.py | 1,321 | 3.59375 | 4 | class TrieNode():
def __init__(self, char):
self.char = char
self.children = []
self.word_complete_indicator = False
self.counter = 1
def add_name(root, string):
node = root
for char in string:
found_in_child = False
for child in node.children:
... |
14cc76243d6e2c004e5f7779c3dd0a4d01db4f61 | hunthunt2010/compilers | /ToTheAST/node.py | 1,123 | 3.53125 | 4 |
class Node:
count = 0
def __init__(self, name, data):
self.name = Node.count
Node.count += 1
self.data = data
#index 0 in child list = left most child
self.children = []
def addChild(self, newChild):
self.children.append(newChild)
def isLeaf(self):
... |
dcd8932c6a3671ea639316e5d6e970ae9997e5e1 | Glitch95/InterviewPrep | /0287-Find-the-Duplicate-Number/solution.py | 1,350 | 3.65625 | 4 | class Solution:
def findDuplicate(self, nums):
# If we weren't constrained to O(1) Space, we
# could easily find the answer in lnear time and
# space by using a set.
# Solution 1 - Floyd's Cycle Detection Algorithm
# O(n) Time, O(1) Space
# If we interpret nums such... |
8762d6dd7eb66a93ab575d812c9fd89f5d0140ee | Glitch95/InterviewPrep | /0084-Largest-Rectangle-in-Histogram/solution.py | 1,487 | 3.703125 | 4 | class Solution:
def largestRectangleArea(self, heights):
# Using a Stack
# Time O(n), Space O(n)
# We will use a stack based algorithm to solve this problem
# 1. Add to the stack if the current height is greater than
# or equal to the top of the stack.
... |
d53a74703939286b519912bb7e853d04e2cd22ae | Glitch95/InterviewPrep | /0042-Trapping-Rain-Water/solution.py | 3,761 | 3.859375 | 4 | class Solution:
def trap(self, height):
# SOLUTION 1 - Dynamic Programming
# O(n) Time O(n) Space
# The water trapped above a bar is the
# height of water that is above it,
# since the width is 1.
# This works out to be min of the max height to
# the left and... |
e28e4798438c5da717ef4699ea5762faa60ec6b6 | Glitch95/InterviewPrep | /0515-Find-Largest-Value-in-Each-Tree-Row/solution.py | 833 | 3.90625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def largestValues(self, root):
# Solution 1 - Iterative Level Order Traversal
# O(n) Time, O)(n) Space
if not ro... |
3557f20aca6ffa0a444a6ddc77061594e54b8c4c | Glitch95/InterviewPrep | /0074-Search-a-2D-Matrix/solution.py | 808 | 3.765625 | 4 | def getIndex(row, col, num_cols):
return row * num_cols + col
def getRowCol(index, num_cols):
return index // num_cols, index % num_cols
class Solution:
def searchMatrix(self, matrix, target):
# Solution 1 - Binary Search
# If m and n are the dimensions of the matrix:
# O(log(mn)) ... |
32f441ffbd620090a780fa10f58a6362ee5cb11a | Glitch95/InterviewPrep | /0173-Binary-Search-Tree-Iterator/solution.py | 1,868 | 3.9375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# Solution 1 - Sorted Array (Recursive Inorder Traversal)
# class BSTIterator:
# def __init__(self, root):
# self.queue = []
# self.inde... |
37f9eaef1ee254f998bd99ee51c7b63221be55ed | Glitch95/InterviewPrep | /0023-Merge-k-Sorted-Lists/solution.py | 1,046 | 4.03125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
from heapq import heapify, heappush, heappop
class Node:
""" Wrapper class to enable comparing nodes """
def __init__(self, node):
self.node = node
def __lt__(... |
572ebe2b33cfa57c7857805d53296c76b5bedb77 | Glitch95/InterviewPrep | /0785-Is-Graph-Bipartite/solution.py | 2,310 | 3.84375 | 4 | def dfs(start, graph, color):
# We arbitrarily chose 0 as the starting color (set) for top level nodes
# i.e. the first node visited in a part of the graph that
# is disjoint from the rest.
if start not in color:
color[start] = 0
for neighbor in graph[start]:
if neighbor in color:
... |
f15a6b4b7b9a0773b9a68997739c04790a203302 | Glitch95/InterviewPrep | /0017-Letter-Combinations-of-a-Phone-Number/solution.py | 903 | 3.75 | 4 | class Solution:
def letterCombinations(self, digits):
# Solution 1 - Iterative Backtracking
# O(n^k) Time - where k is the average number of letters a digit
# maps to and n is the total number of digits in the string.
# O(n) Space
if not digits:
return []
... |
3bbdb091f3f0afd7ee58958a94ba72895fb3aa8e | AAlfaro29/Phyton | /list_exer.py | 702 | 4.25 | 4 | #foods = ["orange", "apple", "banana", "strawberry", "grape", "blueberry",["carrot", "cauliflower","pumpkin"], "passionfruit", "mango", "kiwifruit"]
#print(foods[0])
#print(foods[2])
#print(foods[-1])
#print(foods[0:3])
#print(foods[7:12])
#print(foods[-5]) - Needs to ask
#names= ["Chilli","Roary", "Remus", "Prince Th... |
dd576e1c22751f2eaf3815681f410970815442ad | AAlfaro29/Phyton | /dictionary.py | 972 | 3.703125 | 4 | # Q1
# groceries = {
# "Baby Spinach": 2.78,
# "Hot Chocolate": 3.70,
# "Crackers": 2.10,
# "Bacon": 9.00,
# "Carrots": 0.56,
# "Oranges": 3.08
# }
# quantity = {
# "Baby Spinach": 1,
# "Hot Chocolate": 3,
# "Crackers": 2,
# "Bacon": 1,
# "Carrots": 4,
# "Oranges": 2
# }
# for ke... |
f4a86e68792555c2748f7a69271976efc50f7f85 | rbirkaur23/stringcomparetwo | /stringgreaterorlesser.py | 108 | 4.0625 | 4 | s1="Apple"
s2="Pineapple"
if s1>s2:
print("s1 is greater than s2")
else:
print("s2 is greater than s1")
|
07df30c81da2f806e65c161808b339625c45b1d2 | icanwalkonwater/AdventOfCode_2017 | /app/day4.py | 794 | 3.515625 | 4 | from app.day import Day
class Day4(Day):
def part_1(self):
lines = [l.split() for l in self.input.splitlines()]
print(len([l for l in lines if self.is_line_valid(l)]))
def part_2(self):
lines = [l.split() for l in self.input_2.splitlines()]
valid = 0
for line in lines:
try:
for i, word in enumera... |
5491e1700d0f776b3a63a09fd6a0af578cc18744 | gracepetryk/TSP_Project | /PointNetwork.py | 1,766 | 3.828125 | 4 | """"
Author: Grace Petryk
Simple class encoding the network of points into a data structure
"""
import math
import typing
from typing import List, Tuple
class PointNetwork:
points: List[Tuple[int, int]]
def __init__(self, file_name):
"""
Initializes the graph based on points defined in a f... |
101fd4436e01c4efa2d2309dfefdf865e7c22c6f | jixcoy/DogRunner | /main.py | 6,148 | 3.734375 | 4 | """
------------------------------------------------------------------------------------------------------------------------
Name: John Ixcoy | Unit: 2 | Assignment: Unit 3 Project
Due Date: 10 / 27/ 2021
Description:
This is a runner game made using the pygame module. It has a player that can dodge obstacles ... |
bef0951338fac90252e31532798b1e5e08368d31 | ItsMe-Adi/Tic-tac-toe | /Project-Tic_Tac_Toe.py | 3,521 | 4.21875 | 4 | # TIC TAC TOE game
#--------Global Varaibles--------
#GAME BOARD
board=["-","-","-",
"-","-","-",
"-","-","-"]
#If game is still going
game_still_going=True
#Who win or tie?
winner=None
#Whose turn is it?
current_player="X"
#To display board
def display_board():
print(board... |
95a9f66ffa420c28fbcdd200a67b2b500013aca7 | PratyushTheCoder/The-Wiki-Searcher | /WikiApp/App.py | 2,307 | 3.625 | 4 | # My first big app project which searches the wikipedia for you and shows you the result in the app
from tkinter import *
from time import sleep
import wikipedia
from os import *
app=Tk()
# Creating app visuals
app.geometry('320x396+0+0')
app.title('My Wiki')
app.minsize(width=320, height=396)
app.maxsize... |
dc81ad908f40eeb60f5c16e3d6aa983793f80a8b | kritikanigam09/Python-Basics | /dictionariesexamples.py | 931 | 3.953125 | 4 | menu = {}
menu['Chicken Alfredo'] = 14.50
print(menu['Chicken Alfredo'])
print("There are " + str(len(menu)) + "items on the menu")
print(menu)
beatles = ["john", "paul", "george", "ringo", "stuart"]
beatles.remove("stuart")
print(beatles)
my_dict = { "fish": ["c", "a", "r", "p"],
"cash": -4483,
"luck": "good"
}
prin... |
34666815aa9ea96c0efb21770f4fc9b5f6bc9434 | kritikanigam09/Python-Basics | /Ifexamples.py | 865 | 3.828125 | 4 | def using_control_once():
if 2>1:
return "Success #1"
def using_control_again():
if 45<99:
return "Success #2"
print(using_control_once())
print(using_control_again())
def greater_less_equal_5(answer):
if answer>5:
return 1
elif answer<5:
return -1
else:
return 0
print(greater_less_equal_5(4... |
f4808d1b4c545e018c01e59ffdc98d35e2a54063 | kritikanigam09/Python-Basics | /simpleloopexamples.py | 342 | 3.6875 | 4 | n = 1
while n<=10:
print(n**2)
n +=1
choice =input('Enjoying the course?(y/n)')
while choice != 'y' and choice != 'n':
choice = input("Sorry, I didn't catch that. Enter again: ")
count = 0
while count<10:
print(count)
count +=1
counts = 0
while True:
print(counts)
counts +=1
if coun... |
cf4390304a622b426d4fb836f8cb8cbbaa92734e | zohuhuozwin/learngit | /thief.py | 460 | 3.890625 | 4 | # encoding: utf-8
"""
抓了a,b,c,d4名犯罪嫌疑人.其中有一名是小偷,审讯中
a说我不是小偷
b说c是小偷
c说小偷肯定是d
d说c胡说
其中有3个人说的是实话,一个人说的是假话,编程推断谁是小偷。
(用穷举法和逻辑表达式)
"""
for thief in ["a", "b", "c", "d"]:
sum = (thief != 'a') + (thief == 'c') + (thief == 'd') + (thief != 'd')
if sum == 3:
print("thief is: %s " % thief)
|
9fd445ea49278ad022b33c96b4760dedf1ac4c50 | mworrall1101/code-from-school | /CSC_265/table_to_csv.py | 1,542 | 3.5 | 4 | # table_to_csv.py
# Converts a table in HTML format and converts it to CSV
# All spaces and tabs are collapsed to a single space. EG: Tom Arnold -> Tom Arnold
# If any row in a table is less than the max row length for the given table, the row is
# padded with empty cells at the end.
# Output is in the form:
#
# ... |
a77337033844a34a195464726ccf9f8c5a538dd5 | mworrall1101/code-from-school | /CSC_265/merge_testcase/compare.py | 556 | 3.515625 | 4 | import os
import sys
args = sys.argv
my_file = args[1]
model_file = args[2]
def parse_file(file_name):
f = open(file_name)
table = []
for line in f:
row = line.split(',')
if row[0].strip() == '':
continue
table.append(row)
f.close()
return table
my_table = parse_file(my_file)
model_table = parse_f... |
39113ba692269c24d4eaf98ee6d54fe100b75365 | mworrall1101/code-from-school | /summer16/Week09/string_stuff.py | 427 | 4.15625 | 4 | # string_stuff.py
#
#
#
# B. Bird - 06/28/2016
S = ' Pear, Raspberry, Peach '
#The .split() method of a string splits the string
#by the provided separator and returns a list
#of the resulting tokens.
for token in S.split(','):
print("Token: '%s'"%token)
#The .strip() method of a string removes all lead... |
6c65ae14fe12a85962831ef02916cf7e2802e351 | cassiopagnoncelli/hacker-rank-solutions | /botclean.py | 1,003 | 3.765625 | 4 | # Manhattan distance.
def distance(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def parse_board(bot, board):
d = []
closest_dirty = 0
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == 'd':
d.append([ i, j, distance(bot, [i,j]) ])
if d[len(d)-1][2] < d[closest_dirty][2]:... |
b5cd54f8d1c431b3f850bec609e5ed95bfef031f | cassiopagnoncelli/hacker-rank-solutions | /fibonacci-modified.py | 196 | 3.734375 | 4 | def fib_mod(a, b, n):
if n == 0:
return a
elif n == 1:
return b
for i in range(n-1):
b, a = b**2 + a, b
return a
a, b, n = map(int, raw_input().split())
print fib_mod(a, b, n) |
dac8b901c957b65d9e2e9c4d9cdcb28888c02714 | cassiopagnoncelli/hacker-rank-solutions | /pangrams.py | 261 | 3.578125 | 4 | def pangram(s):
p = map(lambda x: ord(x) - ord('a'), list(s.lower()))
h = [0] * 26
for c in p:
if c >= 0 and c <= 25:
h[c] += 1
for c in h:
if c == 0:
return False
return True
if pangram(raw_input()):
print "pangram"
else:
print "not pangram"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.