blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
ebb48ef97e31747fd970e26e24d374e1e53b8a50 | codesurvivor/kyupy | /kyupy/circuit.py | 9,133 | 3.78125 | 4 | from collections import deque
class GrowingList(list):
def __setitem__(self, index, value):
if index >= len(self):
self.extend([None] * (index + 1 - len(self)))
super().__setitem__(index, value)
class IndexList(list):
def __delitem__(self, index):
if index == len(self) - ... |
d474c2ba8be218314f73b30b142e1b86613ed11d | TestID22/rip_nec0der | /BrainFuck.py | 2,056 | 3.53125 | 4 | def block(code):
opened = []
blocks = {}
for i in range(len(code)):
if code[i] == '[':
opened.append(i)
elif code[i] == ']':
blocks[i] = opened[-1]
blocks[opened.pop()] = i
return blocks
def parse(code):
return ''.join(c for c in code ... |
c954b3d5067de813172f46d1ce5b610a5adc6317 | LL-Pengfei/cpbook-code | /ch2/vector_arraylist.py | 421 | 4.125 | 4 | def main():
arr = [7, 7, 7] # Initial value [7, 7, 7]
print("arr[2] = {}".format(arr[2])) # 7
for i in range(3):
arr[i] = i;
print("arr[2] = {}".format(arr[2])) # 2
# arr[5] = 5; # index out of range error generated as index 5 does not exist
# uncomment the line above to see the error
arr.append... |
9a19d8a9baea1b461e4db02364113fae3d367297 | guojiangwei/myLeetCode | /py/88.合并两个有序数组.py | 1,826 | 3.515625 | 4 | #
# @lc app=leetcode.cn id=88 lang=python3
#
# [88] 合并两个有序数组
#
# @lc code=start
class Solution:
# 将nums2拷贝给nums1
# 排序nums1
# 此方法有点取巧
# 32ms 97% 56% 13.4MB
def merge1(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 i... |
57c08dccb6e36f1116e3c23529459c8e15b83ef9 | jfblanchard/optical-calculations | /optical_calcs.py | 5,662 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
A module containing a number of functions used for performing common
optical calculations
"""
import numpy as np
import matplotlib.pyplot as plt
import scipy.constants as const
import seaborn as sns
sns.set_style('whitegrid')
def diff_limited_spot(wavelength, f,D):
... |
147fc69a868a4dc3e73f317d70596f2a74cb4457 | xiaochenchen-PITT/CC150_Python | /Leetcode/Pascal's Triangle II.py | 488 | 3.5625 | 4 | class Solution:
# @return a list of integers
def getRow(self, rowIndex, pas = [1]):
'''hint: only O(N) extra space, meaning storing from 0th to nth lists is not allowed.'''
if len(pas)-1 == rowIndex:
return pas
next_pas = [1]
for i in range(0, len(pas)):
i... |
fdb3b91793bf1541e2216b8f0384f6ee111983c4 | xiaochenchen-PITT/CC150_Python | /Leetcode/Search in Rotated Sorted Array_return boolean.py | 682 | 3.75 | 4 | class Solution:
# @param A, a list of integers
# @param target, an integer to be searched
# @return an integer
def search(self, A, target):
if len(A) < 3:
return True if target in A else False
mid = (len(A)-1) / 2
if A[0] < A[mid]: # left sorted
if target ... |
039e8c37b1c95e7659c109d2abbef9b697e7ca3d | xiaochenchen-PITT/CC150_Python | /Design_Patterns/Factory.py | 2,731 | 4.78125 | 5 | '''The essence of Factory Design Pattern is to "Define a factory creation
method(interface) for creating objects for different classes.
And the factory instance is to instantiate other class instances.
The Factory method lets a class defer instantiation to subclasses."
Key point of Factory Design Pattern is--
Only ... |
0d51133b3bdbcb43ffd745eeb543c357ff5a4faa | xiaochenchen-PITT/CC150_Python | /Design_Patterns/MVC.py | 2,175 | 4.03125 | 4 | import Tkinter as tk
class Observable:
"""class Observable defines the infrastructure of
model/view register and notification"""
def __init__(self, InitialValue = 0):
self.data = InitialValue
self.observer_list = []
def RegisterObserver(self, observer):
self.observer_list.append(observer)
def ObserverNot... |
38d272cf81d92ed5616d14169f82118ee045f5be | xiaochenchen-PITT/CC150_Python | /cc150/c1.py | 6,214 | 3.9375 | 4 | '''1.1 Implement an algorithm to determine if a string has all unique character
What if you can not use additional data structures?'''
def solution(s):
# # for each in s:
# # if s.count(each) > 1:
# # return False
# # return True
# # if count()is not allowed,
# # then we can sort (quick or merge) the lis... |
224ad7e01779ebc872a2c4c65be799ab0518094f | xiaochenchen-PITT/CC150_Python | /Leetcode/Merge Sorted Array.py | 686 | 3.609375 | 4 | class Solution:
# @param A a list of integers
# @param m an integer, length of A
# @param B a list of integers
# @param n an integer, length of B
# @return nothing
def merge(self, A, m, B, n):
'''Note: A is actually [1, 3, 6, placeholder, placeholder], m = 3
B is [2, 5], n = 2
So avoi... |
6ce064242cb40428e52917203518b1291ceeb0e5 | emetowinner/python-challenges | /Phase-1/Python Basic 2/Day-26.py | 2,807 | 4.5625 | 5 | '''
1. Write a Python program to count the number of arguments in a given function.
Sample Output:
0
1
2
3
4
1
2. Write a Python program to compute cumulative sum of numbers of a given list.
Note: Cumulative sum = sum of itself + all previous numbers in the said list.
Sample Output:
[10, 30, 60, 100, 150, 210, 217]
[1... |
48449d264326a4508b0f111d19a6f5832155485d | emetowinner/python-challenges | /Phase-1/Python Basic 2/Day-28.py | 2,740 | 4.375 | 4 | '''
1. Write a Python program to check whether two given circles (given center (x,y) and radius) are intersecting. Return true for intersecting otherwise false.
Sample Output:
True
False
2. Write a Python program to compute the digit distance between two integers.
The digit distance between two numbers is the absolute... |
c04ddba01766923e3e435d0f5eee406a99d29e17 | Osraj/Tic-Tac-Toe_Game | /Main.py | 3,822 | 3.953125 | 4 | # Tic-Tac-Toe game in Python with simple AI
board = [' ' for x in range(10)]
def insertLetter(letter, pos):
board[pos] = letter
def spaceIsFree(pos):
return (board[pos] == ' ')
def printBoard(board=board):
# print(' | |')
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
# print... |
d8a9bd9a1f48d42de21a646dc5b51ec262ef3c07 | Bloodika/AdventOfCode2020 | /Day3/3.py | 847 | 3.953125 | 4 | def slopes(tree_map, right, down):
index, row, tree_counter = 0, 0, 0
text_length = len(tree_map[0])
while row != len(tree_map) - 1:
index += right
row += down
if index >= text_length:
index = index - text_length
position = tree_map[row][index]
if positio... |
01c8736466d21a74a166999bacededf7f81eeb03 | airmax11/seleniumPy | /Teclado/start.py | 513 | 4.0625 | 4 | class Bookshelf:
def __init__(self, *books):
self.books = books
def __str__(self):
return f"There are {len(self.books)} books."
class Book:
def __init__(self, name, amount):
self.name = name
self.amount = amount
def __str__(self):
return f"Book name is {self.n... |
73b3d4ea858146efa6fa0c26b0e4130d1448c2ea | juanman2/mlpy | /notebook/api_data_wrangling_mini_project.py | 3,435 | 3.828125 | 4 | #!/usr/bin/env python
# coding: utf-8
# This exercise will require you to pull some data from the Qunadl API. Qaundl is currently the most widely used aggregator of financial market data.
# As a first step, you will need to register a free account on the http://www.quandl.com website.
# After you register, you will ... |
c0233475b282a3a4f41a5829905d9fcd1fd0fa69 | lmiguelgarcia/Frubana | /ejercicio2.py | 4,002 | 3.84375 | 4 | import numpy as np
class TreeNode:
"""Clase para crear los nodos del arbol
Atributos
----------
val : int
valor del nodo
left : TreeNode
nodo hijo a la izquieda
right : TreeNode
nodo hijo a la derecha
root : TreeNode
nodo padre
is_leaf : Boo... |
6ece47524c7619b649fd02a684262c06eac17f53 | Megha2122000/python3 | /3.py | 361 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 19 15:30:29 2021
@author: Comp
"""
# Python program to print positive Numbers in a List
# list of numbers
list1 = [-12 , -7 , 5 ,64 , -14]
# iterating each number in list
for num in list1:
# checking condition
if n... |
ccad48e6c0098ebc9f19b8218034baada0a18a53 | sushrest/machine-learning-intro | /decisiontree.py | 1,455 | 4.4375 | 4 | # scikit-learn Machine Learning Library in python
# Environment Python Tensorflow
# Following example demonstrates a basic Machine Learning examples using
# Supervised Learning by making use of Decision Tree Classifier and its fit algorithm to predict whether the given
# features belong to Apple or Orange
from sklea... |
95c41253866a25394ad1c99a3ea2e66580e4f340 | InonBr/python_JS_react | /python_fundamentals/function.py | 170 | 4.0625 | 4 | def double(x):
return x*2
print(double(3))
def multiply(a, b):
result = a * b
print("the result of a * b")
return result
result = multiply(2, 3)
print(result)
|
048c443d33c916c112433ae0358e5b66b1d2ec5c | statco19/doit_pyalgo | /ch3/ssearch_test1.py | 418 | 3.796875 | 4 | from ssearch_while import seq_search
print("Finding a float.")
print("Caurtion: the program quits when 'End' entered")
number = 0
x = []
while True:
s = input(f'x[{number}]: ')
if s == "End":
break
x.append(float(s))
number += 1
ky = float(input("What to search?: "))
idx = seq_search(x,... |
1ed4644c963103b0bb9acc9f5e86fc4b3820321c | statco19/doit_pyalgo | /ch6/quick_sort1.py | 466 | 3.90625 | 4 | def qsort(a, left, right): # left = 0, right = n-1
n = len(a)
pl = left
pr = right
x = a[(left+right)//2]
while pl <= pr:
while a[pl] < x: pl += 1
while a[pr] > x: pr -= 1
if pl <= pr:
a[pl], a[pr] = a[pr], a[pl]
pl += 1
pr -= 1
if left < pr: qsort(a, left, pr)
if right > pl: qsort(a, pl,... |
078583a747845399770de5ca3d4228d66f3ffb3c | statco19/doit_pyalgo | /ch6/quick_sort2.py | 1,071 | 3.828125 | 4 | # choosing a pivot
def sort3(a, idx1, idx2, idx3):
if a[idx2] < a[idx1]: a[idx1], a[idx2] = a[idx2], a[idx1]
if a[idx3] < a[idx2]: a[idx2], a[idx3] = a[idx3], a[idx2]
if a[idx2] < a[idx1]: a[idx1], a[idx2] = a[idx2], a[idx1]
return idx2
# insertion sort
def insertion_sort(a, left, right):
for i in range(left+1... |
eff1131fddbee28b9b4a2c9f7f32ca1a1c38bd94 | statco19/doit_pyalgo | /ch4/fixed_stack_test.py | 1,406 | 3.71875 | 4 | from enum import Enum
from fixed_stack import FixedStack
Menu = Enum("Menu",['push','pop','peek','find','dump','quit'])
def select_menu() -> Menu:
s = [f'({m.value}){m.name}' for m in Menu]
while True:
print(*s, sep = ' ', end = '')
n = int(input(': '))
if 1 <= n <= len(Menu):
... |
27248e5f2992f91b95a1071696682cb0123cc34b | ajm188/coursework | /eecs440/pa3/logistic_regression.py | 5,481 | 3.609375 | 4 | # -*- coding: utf8 -*-
"""
The Logistic Regression Classifier
"""
from __future__ import division
from __future__ import print_function
import numpy as np
import numpy.linalg
import numpy.random
import scipy
import scipy.optimize
import stats
from folds import get_folds
def sigmoid(x):
"""
Computes the sigm... |
b0d5b1f2fa14e151645767ef1bc5e002a4d29476 | jdalton92/cs50x | /pset7/similarities/helpers.py | 813 | 3.53125 | 4 | from nltk.tokenize import sent_tokenize
def lines(a, b):
"""Return lines in both a and b"""
a_line = set(a.split("\n"))
b_line = set(b.split("\n"))
return list(a_line & b_line)
def sentences(a, b):
"""Return sentences in both a and b"""
a_sentence = set(sent_tokenize(a))
b_sentence = ... |
07f17fd5c38fd55a2e8cc668e853e15ebdcb5c73 | poio90/perceptron-multicapa | /cargar_datos.py | 1,722 | 3.59375 | 4 | import pandas as pd
import numpy as np
def cargar_datos(path:str):
"""
dado el path, retorna una tupla con= un numpy.narray primer array filas, segundo array valores de las columnas
con= numpy.narray donde solo tiene valores de la ultima columna del dataset.
"""
data_set_diabetes = pd.read_csv(path... |
edb5a32cde65084ef08906bd501682cc57d37d31 | poio90/perceptron-multicapa | /entrenamiento.py | 2,369 | 3.640625 | 4 | import numpy as np
def entrenar(red_neuronal, Entrada, Respuesta, funcion_costo, tasa_aprendizaje=0.05, entrenar=True):
"""Si entrenar esta en true, se obtiene los resultados del forward_pass, luego se hace el proceso de backpropagation
donde se calculan los deltas, y luego con esto se realiza el aprendizaje ... |
958b94f5966c36f1895d6c183d3cf7459c45a4ad | Sakhiyev/Web-Development | /Web Development/Lab7/informatics/2-ссылка/bolshe.py | 108 | 3.734375 | 4 | a=int(input())
b=int(input())
if(a>b):
print(a)
elif(a==b):
print("Oni ravny")
else:
print(b)
|
8604d0ef3683a455d7281e5139cae4080e5b28d0 | mdmuneerhasan/python | /Hackeblock/test.py | 97 | 3.6875 | 4 | lst = [(1, 2), (2, 2), (3, 2)]
print(lst[1][0])
for i in range(0,3):
print(lst[i])
i+=1 |
3dbaa10acd3bb6edd33d7d86afc4b795da5ef098 | rishgoyell/VisProgGen | /token_file.py | 1,445 | 3.609375 | 4 | '''
This file contains the definitions of tokens required
to tokenize the program
'''
import ply.lex as lex
def build_lexer(debug_mode=True, optimize_mode=False):
tokens = [
'IDENTIFIER',
'UNION',
'INTERSECTION',
'DIFFERENCE',
'INTEGER'
]
literals = "(),"
# t_t... |
d7c34077050555f47e8e1988e1a49b2f27fdc4b2 | inwk6312winter2019/openbookfinal-arjanchauhan87 | /task1B.py | 197 | 3.625 | 4 | def count_the_article():
mylist = ["a", "the", "at", "run", "to","and","are","or","for","an","this"]
for x, word in enumerate(mylist):
for i, subwords in enumerate(word):
print i
|
e5a138e01d5f8068025cffb859ae3324fe73a456 | alimohammad0816/algorithms | /rotate.py | 163 | 3.546875 | 4 | def rotate(s, k):
duble_s = s + s
if k <= len(s):
return duble_s[k:k+len(s)]
else:
return duble_s[k-len(s):k]
print(rotate("ali", 5)) |
84d6cd6702409ee551f0383a14bf3b4b64aa9af2 | alimohammad0816/algorithms | /buy_sell_stock.py | 339 | 3.578125 | 4 | """
buy-sell stock
[7, 1, 5, 3, 6, 4] ==> 5
[9, 7, 6, 4, 3, 1] ==> 0
"""
def max_profit(prices):
cur_max, final_max = 0, 0
for i in range(1, len(prices)):
cur_max = max(0, cur_max + prices[i] - prices[i - 1])
final_max = max(cur_max, final_max)
return final_max
max_profit([... |
6c9bf76c320d9c711c254c6c6c057ecb3abae949 | POA-WHU/POA-spiders | /src/base/base_url_manager.py | 2,389 | 3.5 | 4 | """
BaseURLManager定义文件
"""
from threading import Thread
from abc import ABC, abstractmethod
from base.utilities import Logger
class BaseURLManager(ABC):
"""
从目录页获取文章URL,为Spider提供待爬取的URL
"""
def __init__(self, start_page=1, end_page=-1):
"""
初始化
注意:每个目录页包含多个url
:param... |
fc97aa36a7e1b41c72b120769e49972655d38f3f | RatnadeepYSVS/Algorithms | /Smallest Positive missing number .py | 1,578 | 3.890625 | 4 | """
Question:You are given an array arr[] of N integers including 0.
The task is to find the smallest positive number missing from the array.
Example 1:
Input:
N = 5
arr[] = {1,2,3,4,5}
Output: 6
Explanation: Smallest positive missing number is 6.
Example 2:
Input:
N = ... |
ccc3abda28abe8e4719c043e55fe47fe3e9f7b53 | fight741/DaVinciCode | /main.py | 435 | 4.15625 | 4 | import numpy as np
start = input("start from : ")
end = input("end with : ")
number = int(np.random.randint(int(start), int(end)+1))
g = int(input("Input your guess here : "))
while g != number:
if g > number:
print("The number is smaller")
g = int(input("Give another guess : "))
else:
... |
ad1a43b054cdacf6c3db89e33a389df16df0b7da | abhishekshinde2104/Coursera_Guided_Projects | /Image Data Augmentation with Keras/project.py | 5,435 | 3.625 | 4 | #IMPORTING LIBRARIES
#%matplotlib inline
import os
import numpy as np
import tensorflow as tf
from PIL import Image
from matplotlib import pyplot as plt
print('Using TensorFlow', tf.__version__)
#ROTATION
#This class has lot of functions for data augmentation and we can also do data normalisation with ... |
41de36d6f7b3d3daaa24450d1b6e0fa6c97fa431 | antonvsdata/walking_dinner | /src/reader.py | 3,379 | 3.953125 | 4 | import csv
from participant import Participant
import sys
class Reader:
"""
Reader class for the .csv files
Currently, a minimum number of 18 participants is required
"""
def __init__(self, file, delimiter=","):
self.file = file
self.delimiter = delimiter
def check_header(sel... |
cb07bb7e8a75906f636c5b57a9aeb65b564cb89d | SidG404/Course-Work | /OPEN SOURCE/WEEK 4/2.py | 230 | 3.5625 | 4 | import numpy as np
user_input=int(input())
n=user_input
list=[]
while(n!=0):
m=n%10
n=n/10
list.append(m)
list.reverse()
numpy_array=np.array(list)
numpy_array.sort()
numpy_array=numpy_array[::-1]
print(numpy_array)
|
1f603a12707aad4eb77a203c707541b159b0a116 | JavierPacheco1601/StructuredProgramming-2A- | /funtions_intro.py | 1,337 | 4.03125 | 4 | from sys import argv as ag
def addToNumbers( number1, number2 ):
print('StartProgram: addToNumbers executed...\n')
result = number1+number2
return result
answer = False
def isEven( aNumber ):
if( aNumber%2 == 0 ):
return True
# prin... |
e1e57f1b0ef3b9715575a6cea092f052695cefb2 | guyutza/myproject | /Yuze Gu Python Program/mapquest_client.py | 1,560 | 3.53125 | 4 | # Yuze Gu
import mapquest_api
import mapquest_classes_output
class MapQuestError(Exception):
pass
class RouteNotFoundError(Exception):
pass
def input_places() -> list:
'''let user input the locations and orders'''
places_num = int(input())
if places_num < 2:
raise MapQuestError
else:... |
e1056968cd13a605ae4f0ff2cf1b2c3bb7d4459f | wolwemaan/katis | /foxsay.py | 257 | 3.5625 | 4 | def runtest(c):
while True:
j = [str(i) for i in input().split()]
if j[0] == "what":
print (" ".join(c))
return
else:
c = [value for value in c if value != j[-1]]
for n in range(0, int(input())):
runtest([str(i) for i in input().split()])
|
d61ea57024a9f16d89a6f12979fe6d8050209785 | ArkhipovNikita/Breakout | /objects/board.py | 878 | 3.53125 | 4 | import pygame
import random
from helps import Common, width, height
from base_classes import *
class Board(pygame.sprite.Sprite, GameObject):
"""
Class describing behavior of board object
Class inherits GameObject class
Attributes:
step step of moving by key
"""
def __init__(s... |
ce4538035bd10d46defe36ca39677409fad124a8 | AndresMontenegroArguello/UTC | /2020/Logica y Algoritmos/Tareas/Tarea 2/Extras/Python/Tarea 2.1 - Colones.py | 626 | 4.34375 | 4 | # Introducción
print("Logica y Algoritmos")
print("Andres Montenegro")
print("02/Febrero/2020")
print("Tarea 2.1")
print("Colones")
print("**********")
# Definición de variables
# Python es de tipado dinámico por lo que no es necesario declarar antes de asignar valor a las variables
# Ingreso de datos por el usuario
... |
5e5d9fe7b10d00f927162e2b39c6eedaa4cb8538 | vijayprathap/PassCheck | /pass.py | 3,288 | 3.9375 | 4 | import re
import random
num_check = re.compile(r"[0-9]")
upp_case = re.compile(r"[A-Z]")
spl_char = set('`~!@#$%^&*()-_=+{[}]|\;:"\'<,>.?/')
#checks if the given password has atleast 6 characters
def sixLetter(password):
if len(password) >= 6:
return True
else:
return False
#checks if the given password has a... |
8bb4ef10fa5bb4e81806cdb797e2a7d857854f37 | mbeliogl/simple_ciphers | /Caesar/caesar.py | 2,137 | 4.375 | 4 |
import sys
# using caesar cipher to encrypy a string
def caesarEncrypt(plainText, numShift):
alphabet = 'abcdefghijklmnopqrstuvwxyz '
key = []
cipherText = ''
plainText = plainText.lower()
# the for loop ensures we are looping around
for i in range(len(alphabet)):
if i + numShift >... |
4f481795b00a24195be24d735f5a05e9fa8f5055 | Yoatn/codewars.com | /Largest 5 digit number in a series.py | 1,000 | 3.796875 | 4 | # --------------------------------------------------
# Programm by Yoatn
#
# Start date 04.01.2018 19:47
# End date 04.01.2017 20:07
#
# Description:
#In the following 6 digit number:
# 283910
# 91 is the greatest sequence of 2 digits.
#
# In the following 10 digit number:
#
# 1234567890
# 67890 is the gre... |
83a808d35782977e2ea92f9ed105d73f7d61f443 | strendley/CS3600 | /pa02/bin_otp.py | 2,466 | 3.9375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 20 19:47:56 2019
@author: stbrb@mst.edu
"""
import sys
def main():
keyFile = sys.argv[1] #grab all inputs
keyNum = sys.argv[2]
inFile = sys.argv[3]
outFile = sys.argv[4]
convertedString = convertInput(inFile) #convert the ... |
8178b51bf3c1385ae1aa3c4fa1684e535be6357e | suay1936/suay1936-cmis-cs2 | /countup.py | 190 | 3.65625 | 4 | def countup(n):
if n >= 10:
print "Blast off"
else:
print n
countup(n + 1)
def main():
countup(0)
countup(1)
countup(-20)
return
main()
|
bbe8a937b2109cc02dcc2059d87a1e505b4bbc13 | suay1936/suay1936-cmis-cs2 | /simpleprogram.py | 1,702 | 3.921875 | 4 | # simpleprogram: currency conversion
import math
def baht_to_dollar(dollar1):
dollar1 = dollar1 / 35.63
def baht_to_pound(pound1):
pound1 = pound1 / 50.94
def dollar_to_baht(baht1):
baht1 = baht1 * 35.63
def dollar_to_pound(pound2):
pound2 = pound2 * 0.70
def pound_to_baht(baht2):
... |
791db67ad389cdc6364342f60d73e9556877c0d3 | suay1936/suay1936-cmis-cs2 | /oneguess.py | 1,053 | 4.09375 | 4 | # What is the minimum number? 5
# What is the maximum number? 10
# I'm thinking of a number from 5 to 10.
# What do you think it is?: 7
# The target was 9.
# Your guess was 7.
# That's under by 2.
#need to use the if an comparison
# interval comparison
import random
import math
#adjust lines with def, check th... |
89e0b00936b4f58aaa57beb6545c6f9e6008b48f | tmrd993/pythonchallenge | /ch6.py | 809 | 3.625 | 4 | from zipfile import ZipFile
zip = ZipFile('ch6.zip', 'r');
print(zip.getinfo('90052.txt').comment);
pathPrefix = 'ch6/';
fileType = '.txt';
filename = "90052";
fileContents = open(pathPrefix + filename + fileType, "r").read();
filename = fileContents[fileContents.index('is') + 3:];
print(str(zip.getinfo(filename + f... |
f62be8e37d8707398922cd9a310a8670fb7a5527 | JohnnyHowe/slow-engine | /display/camera.py | 869 | 3.546875 | 4 | from slowEngine.vector2 import Vector2
class Camera:
""" Camera class.
Uses singleton pattern.
Deals with game/world display things.
"""
# Singleton things
_instance = None
@staticmethod
def get_instance():
if Camera._instance is None:
Camera()
return Camer... |
4d969849727d7b049825d2dcf47db14b7dd16a67 | AndrewBowerman/example_projects | /Python/oopRectangle.py | 1,745 | 4.5625 | 5 | """ oopRectangle.py
intro to OOP by building a Rectangle class that demonstrates
inheritance and polymorphism.
"""
def main():
print ("Rectangle a:")
a = Rectangle(5, 7)
print ("area: {}".format(a.area))
print ("perimeter: {}".format(a.perimeter))
print ("")
print ("Rectan... |
35e90299fb38758fadf25e5a037bb62e618d47e3 | countone/exercism-python | /beer_song.py | 842 | 3.96875 | 4 | def recite(start, take=1):
song=[]
while take>0:
if start==0:
song.append('No more bottles of beer on the wall, no more bottles of beer.')
song.append('Go to the store and buy some more, 99 bottles of beer on the wall.')
elif start==1:
song.append('1 bottle of beer on the wall,... |
63aa75a90f9b31c9959afd8eb59807253efabdbc | countone/exercism-python | /diamond.py | 620 | 3.90625 | 4 | from string import ascii_uppercase as UPPER
def make_diamond(letter):
diamond=[]
for i in range(UPPER.index(letter)+1):
if i==0:
diamond.append((UPPER.index(letter)-i)*' '+UPPER[i]+(UPPER.index(letter)-i)*' ')
else:
diamond.append((UPPER.index(letter)-i)*' '+UPPER[i]+(i*2-1)*' '+UPPER[i]+(UPPER.index(lette... |
f637572b76b214df0d5f99698c7194e5d3ce92b9 | countone/exercism-python | /allergies.py | 895 | 3.90625 | 4 | class Allergies(object):
def __init__(self, score):
self.score=score
def is_allergic_to(self, item):
return (item in self.lst)
@property
def lst(self):
allergy_list=[]
temp_score=self.score%256
while temp_score>0:
if temp_score>=128:
temp_score-=128
allergy_list.append('cats')
... |
59475aaeebbd95938a0ff08294533c03c59392e1 | countone/exercism-python | /clock.py | 873 | 3.921875 | 4 | class Clock(object):
def __init__(self, hour, minute):
hour+=minute//60
self.minute=minute%60
self.hour=hour%24
def __repr__(self):
if len(str(self.hour))==1 and len(str(self.minute))==1:
return '0'+str(self.hour)+':'+'0'+str(self.minute)
elif len(str(... |
900f7d0045824991014ba4760bcd06867f3c4fbd | countone/exercism-python | /custom_set.py | 1,401 | 3.71875 | 4 | class CustomSet(object):
def __init__(self, elements=[]):
self.elements=set(elements)
def isempty(self):
return not self.elements
def __contains__(self, element):
return element in self.elements
def issubset(self, other):
return self.elements <=other.elements
def ... |
ff473968b091617a36adeabd52181a0b9c6fd27f | yuzhengDL/MSAN | /vocab.py | 1,213 | 3.578125 | 4 | """
Constructing and loading dictionaries
"""
import numpy
from collections import OrderedDict
from collections import Counter
def build_dictionary(text):
"""
Build a dictionary
text: list of sentences (pre-tokenized)
"""
counter = Counter()
captions = []
for s in text:
tokenized_captions = []
s = s.lower()... |
eb32a71508ff54d97244320b409274f2a06e4253 | singhankur7/Python | /classes ass.py | 3,623 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 20 22:53:14 2019
@author: Ankur Singh
"""
"""
Python is easy : Homework assignment #9
Classes
"""
# creating a class
class Vehicle:
def __init__(self, make, model, year, wt, TSM, NM): #declaring class attributes
self.make = make
... |
6f7d33585fac28efdcbd848c65e489bb71044b0b | singhankur7/Python | /advanced loops.py | 2,306 | 4.375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 9 23:48:15 2019
@author: New
"""
"""
Python is easy: Homework assignment #6
Advanced Loops
"""
# for the maximum width(columns) and maximum height(rows) that my playing board can take
# This was achieved by trial and error
# Defining the function which... |
d05538641aeebe5475ec7d5b83c4bab4d6a77296 | NadiaAlmutlak/Intro-Python | /Desktop/IntroPython/Midterm/Midterm Practice/baseball.py | 2,490 | 3.71875 | 4 | # in the case the csv is provided this code can be directly applicable by just changing the csv name
import csv
comparator_ops = ["min", "max"] # these operators give us the different mathmatical function labels we may use
math_ops = ["sum", "avg"]
valid_op_names = comparator_ops + math_ops # if another label is in... |
5bae9f98d4a044f24784506c634426868a01ae77 | Kenoro1/pop | /3.py | 690 | 4.09375 | 4 | months = int(input('Введите месяц ввиде целого числа: '))
winter = [12, 1, 2]
spring = [3, 4, 5]
summer = [6, 7, 8]
autumn = [9, 10, 11]
if months in winter:
print('Зима')
if months in spring:
print('Весна')
if months in summer:
print('Лето')
if months in autumn:
print('Осень')
# --------------------... |
47e5298eb88a8cb40827b8a0ed5745e0dbcbb74a | sagarneeli/coding-challenges | /Other/cube.py | 805 | 4.0625 | 4 | """
Question:
You have 15 six-sided blocks.
These are cubes with a letter (or a blank space) on each face.
Each block can have a different set of letters.
For instance, one block may have A E I O U _ on its faces;
another block may have A B C D E E.
Write a function that takes as input a 15 character message
and t... |
3c72263a7c1a33651b5ab20d448b57a0810160dc | sagarneeli/coding-challenges | /Arrays/spiral_order.py | 1,028 | 4.0625 | 4 |
"""
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
Game plan
1. Keep 4 pointers top, bottom, left, right
2. Start from the first row and iterate over the columns, top ... |
b6b9a578c524fa372d4adf93096d3a5c29b5c5d0 | sagarneeli/coding-challenges | /Linked List/evaluate_expression.py | 2,583 | 4.59375 | 5 | # Python3 program to evaluate a given
# expression where tokens are
# separated by space.
# Function to find precedence
# of operators.
def precedence(op):
if op == '+' or op == '-':
return 1
if op == '*' or op == '/':
return 2
return 0
# Function to perform arithmetic
# operations.
def applyOp(a, ... |
eccee14c4a5a92446a898f2c1a668b4036122070 | hehao9/Mushroom | /sqlite3_help.py | 3,193 | 3.71875 | 4 | import sqlite3
class Sqlite3DB:
def __init__(self, db_name=None):
self.conn = sqlite3.connect(db_name if db_name else 'system.db')
self.cursor = self.conn.cursor()
def create_table(self, table_name: str, field_list: list):
"""
创建表格
:param table_name: 表名
:param... |
b408fbae9bcbcdcc49651da01f35bfffb92f7b6d | AntoineMau/N-Puzzle | /utils.py | 1,086 | 3.828125 | 4 | def error(index_error):
list_error = {
'Bad file': 'Error: Bad file',
'Unsolvable': 'Error: Puzzle is unsolvable',
'Under size': 'Error: Size must be ≥ 3',
'Under shuffle': 'Error: Number of shuffle must be ≥ 0',
}
print(list_error[index_error])
exit(1)
def swap(data, i1, i2):
data[i1], data[i2] = data[i2... |
668cf41a649c6771f2b239253ef5449fb70f6487 | lesnerd/weary_traveler | /loaders/csv_steps_array_loader.py | 895 | 3.625 | 4 | import pandas
import pandas as pd
class CSVStepsArrayLoader(object):
@staticmethod
def load(file_path):
try:
df = pd.read_csv(file_path, sep=',', header=None, skip_blank_lines=True).dropna()
except pandas.errors.EmptyDataError:
raise pandas.errors.EmptyDataError('No dat... |
6cbceeafb452648885a2cda8a579f917f96265be | dianalow/deeplearning | /softmax.py | 900 | 3.53125 | 4 | """Softmax."""
import numpy as np
scores = np.array([3.0, 1.0, 0.2])
# scores = np.array([[1, 2, 3, 6],
# [2, 4, 5, 6],
# [3, 8, 7, 6]])
def softmax(x):
"""Compute softmax values for each sets of scores in x."""
#pass # TODO: Compute and return softmax(x)
value... |
0a1a0f66af66feb4ee13899192bc64ef2d66f018 | sy-li/ICB_EX7 | /ex7_sli.py | 1,791 | 4.375 | 4 | # This script is for Exercise 7 by Shuyue Li
# Q1
import pandas as pd
def odd(df):
'''
This function is aimed to return the add rows of a pandas dataframe
df should be a pandas dataframe
'''
nrow = df.shape[0]
odds = pd.DataFrame()
for i in range(1,nrow):
if i%2 == 0:
... |
d6ba9957ecd45606826386e031558efca3474a0b | jtanium/turbo-garbanzo | /vehicle_prices.py | 888 | 3.609375 | 4 | import numpy as np
def predict(X, w):
return np.matmul(X, w)
def loss(X, Y, w):
return np.average((predict(X, w) - Y) ** 2)
def gradient(X, Y, w):
return 2 * np.matmul(X.T, (predict(X, w) -Y)) / X.shape[0]
def train(X, Y, iterations, lr):
w = np.zeros((X.shape[1], 1))
for i in range(iteratio... |
70a613a86f90ab97397f9c29797b220793428aa4 | 44746/Lists | /Caesar.py | 652 | 4.03125 | 4 | def input1():
message = input("Please enter the message: ")
cora = input("Is the message in caesar or english? c or e: ")
if cora == "c":
shift = -3
else:
shift = 3
return message,shift
def process(message,shift):
list1 = list(message)
list2 = []
for index in range(... |
385567e7cf206dc047dd799ac28615e9c49525e2 | 44746/Lists | /bubble sort1.py | 405 | 3.734375 | 4 |
list1= []
item = '1'
while item!= "0":
item=input("Please add an item to a list: ")
if item!= "0":
list1.append(item)
no_swaps=False
while no_swaps != True:
no_swaps= True
for count in range (len(list1)-1):
if list1[count]> list1[count+1]:
no_swaps = False
... |
63cf9296c1b57a4e5999d3a077cbdde4bef9fc0c | danu0/Particle_Electric_Field | /run_electron_rk4_1.py | 1,253 | 3.515625 | 4 | from electron_rk4_1 import *
import numpy as np
import matplotlib.pyplot as plt
Ex = 0 #
Ey = 0 #
B = 1e-4 #
t0 = 0.0 # initial time
dt = 1e-9 # integration time step
tmax= 1e-6 # end of integration
x0=0.0 # initial x position
y0=0.0 # initial y position
vx0=100 ... |
c24b76b40773bcde6356d5ba2f951cdd3eea5d94 | io-ma/Zed-Shaw-s-books | /lmpthw/ex4_args/sys_argv.py | 1,302 | 4.4375 | 4 | """
This is a program that encodes any text using the ROT13 cipher.
You need 2 files in the same dir with this script: text.txt and result.txt. Write your text in text.txt, run the script and you will get the encoded version in result.txt.
Usage:
sys_argv.py -i <text.txt> -o <result.txt>
"""
import sys, codecs
... |
4a0b6ac25992d4fe863ab606b9bba7ac76c2f803 | io-ma/Zed-Shaw-s-books | /lpthw/ex45/diver.py | 609 | 3.703125 | 4 | class Diver(object):
""" Main diver class """
def __init__(self, diver_name):
""" Initialize diver class """
self.name = diver_name
self.choices = {
'instructor_name': 'x',
'cave_name': 'y',
'equipment': []
}
self.points = None
... |
964a73303ef9c60790a12e94a0315b7dce610afb | io-ma/Zed-Shaw-s-books | /lpthw/ex4/ex4_sd3.py | 813 | 3.78125 | 4 | # cars is 100
cars = 100
# space_in_a_car is 4.0
space_in_a_car = 4.0
# drivers is 30
drivers = 30
# passengers is 90
passengers = 90
# cars_not_driven is cars - drivers
cars_not_driven = cars - drivers
# cars_driven is drivers
cars_driven = drivers
# carpool_capacity is cars_driven * space_in_a_car
carpool_capacity = ... |
fce87c3bacfa0a2b794f793c5c8bc62d35015784 | io-ma/Zed-Shaw-s-books | /lmpthw/ex13_sll/sll.py | 4,858 | 3.953125 | 4 | class SingleLinkedListNode(object):
def __init__(self, value, nxt):
self.value = value
self.next = nxt
def __repr__(self):
nval = self.next and self.next.value or None
return f"[{self.value}:{repr(nval)}]"
class SingleLinkedList(object):
def __init__(self):
self.b... |
cdf3e69d108a22b4f439d7f3891be6180e5eff39 | io-ma/Zed-Shaw-s-books | /lpthw/ex7/ex7_sd1.py | 834 | 4.09375 | 4 | # prints a string
print("Mary had a little lamb.")
# prints a string that contains another string
print("Its fleece was white as {}.".format('snow'))
# prints a string
print("And everywhere that Mary went.")
# prints 10 times .
print("." * 10) # what'd that do?
# sets end1 to C
end1 = "C"
# sets end2 to h
end2 = "h"
#... |
87753a54526f92bd132822cfaada8b03ed2f2bbf | io-ma/Zed-Shaw-s-books | /lmpthw/ex4_args/arg_parse.py | 1,078 | 4.09375 | 4 | import argparse
import codecs
import os
def write_result(args, encoded):
""" Write result to the output file """
result = args['text'][:-4] + '_1.txt'
with open(result, 'w') as target:
target.write(encoded)
target.close()
print("Success! Your file is encoded.")
def encode(args):
... |
e015f0925ccb831ef32e805bd81fff3db46668f6 | io-ma/Zed-Shaw-s-books | /lpthw/ex19/ex19_sd1.py | 1,485 | 4.34375 | 4 | # define a function called cheese_and_crackers that takes
# cheese_count and boxes_of_crackers as arguments
def cheese_and_crackers(cheese_count, boxes_of_crackers):
# prints a string that has cheese_count in it
print(f"You have {cheese_count} cheeses!")
# prints a string that has boxes_of_crackers in it
... |
6d61170cc9b78518126f5608a298b0126de37c4e | io-ma/Zed-Shaw-s-books | /lpthw/ex33/ex33_sd5.py | 255 | 3.75 | 4 | def range_func(incr, up_limit):
numbers = []
numbers = range(incr, up_limit)
for number in numbers:
print(f"The number is {number}")
print("The numbers: ")
for number in numbers:
print(number)
range_func(1, 6) |
9b4c2f669637b9726c9c442467bd0a670b1f1fc2 | InnaMisovetc/algorithm_training | /yandex_algorithm_training/contest1/A-conditioner.py | 554 | 3.71875 | 4 | def temp_after_one_hour(t_room, t_cond, mode):
if mode == 'fan':
return t_room
elif mode == 'auto':
return t_cond
elif mode == 'freeze':
if t_cond < t_room:
return t_cond
else:
return t_room
elif mode == 'heat':
if t_cond > t_room:
... |
007b26928ae2db9fa19beb5691406d392af147f3 | blakfeld/Data-Structures-and-Algoritms-Practice | /Python/sorts/util.py | 717 | 4.09375 | 4 | """
util.py -- Common functions to be used by various sorting algorithms.
"""
import random
def swap(l, i, j):
"""
Swap the index i with the index j in list l.
Args:
l (list): list to perform the operation on.
i (int): left side index to swap.
j (int): Right side index to... |
a6da253639d8ca65b62444ec6bc60545c11d2501 | blakfeld/Data-Structures-and-Algoritms-Practice | /Python/general/binary_search_rotated_array.py | 1,661 | 4.34375 | 4 | #!/usr/bin/env python
"""
binary_search_rotated_array.py
Author: Corwin Brown <blakfeld@gmail.com>
"""
from __future__ import print_function
import sys
import utils
def binary_search(list_to_search, num_to_find):
"""
Perform a Binary Search on a rotated array of ints.
Args:
list_to_search (lis... |
38bb553b4974f0df84ce9704955c61d32abfb54c | L200170159/prak_asd | /Modul 2/latOOP3.py | 473 | 3.765625 | 4 | class Manusia(object):
""" class ' manusia' dengan inisiasi 'nama' """
keadaan="lapar"
def __init__(self,nama):
self.nama=nama
def ucapkanSalam(self):
print "salaam, namaku",self.nama
def makan(self,s):
print "saya baru makan",s
self.keadaan="kenyang"
... |
e6d34c8f7107ce16aacb7791b215e97bf60ea0d5 | ChanakaUOMIT/Machine-learning-basic | /matPlotlib-basic/bar-basic.py | 351 | 3.65625 | 4 | import matplotlib.pyplot as plt
from matplotlib import style
style.use('bmh')
x = [2, 4, 6]
y = [3, 6, 9]
x2 = [4, 8, 12]
y2 = [5, 10, 15]
x3 = [6, 12, 18]
y3 = [12, 24, 36]
plt.bar(x, y)
plt.bar(x2, y2)
plt.bar(x3, y3)
plt.title("Test")
plt.xlabel("Test x values")
plt.ylabel("Test y values")
plt.show()
print("... |
cc61c9f756d546638241c8213e5f371390693519 | strawhatRick/python_learning | /list_slice.py | 280 | 3.53125 | 4 | rainbow = ["red", "orange", "green", "yellow", "blue", "black", "white", "aqua", "purple", "pink"]
del rainbow[5:8]
rainbow[2:4] = ["yellow", "green"]
rainbow[4:5] = ["blue", "indigo"]
rainbow[-2:] = "violet"
rainbow[-6:] = ["".join(rainbow[-6:])]
for i in rainbow:
print (i)
|
b60d9a557323fc63fb093135624b57d7b596657e | martireg/bmat | /app/utils/csv_manipulation.py | 966 | 3.546875 | 4 | import csv
from typing import Union, IO, List, Dict, Generator, Iterable, ByteString, Optional
def process_csv(file: Union[IO, str, List[str], bytes]):
if isinstance(file, bytes):
file = file.decode()
if isinstance(file, str):
file = file.splitlines()
return csv.DictReader(file, delimiter=... |
1578f0742d7e2e04bc8fd65c13ee0418612cacea | Braingains/Python-loop-lists | /start_code/task_list.py | 2,342 | 3.859375 | 4 | #chickens = [
# { "name": "Margaret", "age": 2, "eggs": 0 },
# { "name": "Hetty", "age": 1, "eggs": 2 },
# { "name": "Henrietta", "age": 3, "eggs": 1 },
# { "name": "Audrey", "age": 2, "eggs": 0 },
# { "name": "Mabel", "age": 5, "eggs": 1 },
#def find_chicken_by_name( list, chicken_name ):
# for chicken in list... |
a56c0c46f1810e8540a5aaf4dc5e538cc0a80bf5 | Himani1010/loop | /manjula_pettren_2_elif.py | 378 | 3.59375 | 4 | i=1
while i<=4:
j=1
while j<=7:
if (i==1 and(j==1 or j==2 or j==3 or j==5 or j==6 or j==7)):
print(" ",end=" ")
elif(i==2 and(j==1 or j==2 or j==6 or j==7)):
print(" ",end=" ")
elif(i==3 and(j==1 or j==7)):
print(" ",end=" ")
else:
... |
0c6d4979aad84d3ca6c087e5d2980f81ba8739c6 | Himani1010/loop | /q2_to_100.py | 79 | 3.8125 | 4 | i=20
while i<=100:
if i%2==0:
print(i ,"divisible by 2")
i=i+1
|
399d2aa8119607ceabe1c096b798d86ec5fa4a44 | Himani1010/loop | /counter_question_5.py | 130 | 4 | 4 | i=0
sum=0
n=int(input("enter a number"))
while i<n:
n_1=int(input("enter a number"))
sum=sum+n_1
print(sum)
i=i+1
|
cec8a1091bad0447be52deefeda0174293bfefd0 | matyh/PracticePython | /17 Decode A Web Page.py | 451 | 3.796875 | 4 | """
Use the BeautifulSoup and requests Python packages to print out a list of
all the article titles on the New York Times homepage (http://www.nytimes.com/)
"""
import requests
from bs4 import BeautifulSoup
url = "http://www.nytimes.com/"
r = requests.get(url)
soup = BeautifulSoup(r.text, "html.parser")
articles... |
66eca7571cc7335686f71ff78987c7560833432a | katharinepires/cursodepython | /basicos_conceitos.py | 6,159 | 4.1875 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Conceitos básicos:
# In[1]:
X = 10
Y = 25
soma = X + Y #soma recebe x + y, esse é o jeito correto de ler
print("O resultado da adição entre", X, "e", Y, 'é igual a', soma)
# In[2]:
100%2
# In[3]:
100%3
# ### Variáveis numéricas:
# - *int* => significa números inte... |
9196d5de7e76fab9792b793fd62806e13d1ff153 | kparmar20/ProjectEuler | /Q6.py | 453 | 3.765625 | 4 | def sum_of_square(min_int, max_int):
list_out=[]
for x in range(min_int, max_int+1):
list_out.append(x**2)
return sum(list_out)
def square_of_sum(min_int, max_int):
list_out=[]
for x in range(min_int, max_int+1):
list_out.append(x)
return sum(list_out)
#sum of squares
#print(su... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.