blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
8a8db949a7bcb74f2bd393eaeffa0bb1a9be219d | Mukesh-Choubey/Juniper | /practice_comprehensions.py | 653 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 5 10:13:37 2020
@author: mchoubey
"""
x = [x for x in range(5) for y in range(5)]
print(x)
from random import randint
numbers = [x for x in range(0,21,2)]
randin_ints = []
randin_ints = [randint(1, 100) for i in range(20)]
print(numbers, randin_ints)
from math import fa... |
79e30aefd15dbc6d555c7cd6d58cbca4e6764873 | Mukesh-Choubey/Juniper | /table.py | 487 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 5 15:58:58 2020
@author: mchoubey
"""
def table(table=5):
tableend = 10*table+1
for i in range (table, tableend, table):
times = int(i/table)
print(f"{table} X {times} = {i}")
num = (int(input("enter the number for which you need table:-")))
tab... |
c2a3793df59a8369babff3c5ed7888edee44bb79 | OneWinged-Eagle/MyDailyCodingProblem | /Hard/#93.todo/main.py | 1,214 | 4.03125 | 4 | """
Given a tree, find the largest tree/subtree that is a BST.
Given a tree, return the size of the largest tree/subtree that is a BST.
"""
from __future__ import annotations
from math import inf
from typing import Any
class Node:
val: Any
left: Node
right: Node
def __init__(self, val: Any, left: Node = None, ... |
906f30c4f261cf2a037cc1e12c73840bd84d5ac4 | OneWinged-Eagle/MyDailyCodingProblem | /Easy/#65/main.py | 980 | 4.5 | 4 | """
Given a N by M matrix of numbers, print out the matrix in a clockwise spiral.
For example, given the following matrix:
[[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]]
You should print out the following:
1
2
3
4
5
10
15
20
19
18
17
16
11
6
7
8
9
14
13
12
"""
import num... |
72e0bbd300ab6c8b139f7f2f255b0a97ffe6bf12 | OneWinged-Eagle/MyDailyCodingProblem | /Medium/#103/main.py | 1,452 | 4.03125 | 4 | """
Given a string and a set of characters, return the shortest substring containing all the characters in the set.
For example, given the string "figehaeci" and the set of characters {a, e, i}, you should return "aeci".
If there is no substring containing all the characters in the set, return null.
"""
from typing ... |
4035ca9d616d1b8a8b77510949de7118606abd17 | OneWinged-Eagle/MyDailyCodingProblem | /Easy/#311/main.py | 697 | 4 | 4 | """
Given an unsorted array, in which all elements are distinct, find a "peak" element in O(log N) time.
An element is considered a peak if it is greater than both its left and right neighbors. It is guaranteed that the first and last elements are lower than all others.
"""
from typing import List
def peak(array: L... |
84bcedb58de9e6476cfd13d51fabf1875de85f7d | OneWinged-Eagle/MyDailyCodingProblem | /Medium/#151/main.py | 1,153 | 3.796875 | 4 | """
Given a 2-D matrix representing an image, a location of a pixel in the screen and a color C, replace the color of the given pixel and all adjacent same colored pixels with C.
For example, given the following matrix, and location pixel of (2, 2), and 'G' for green:
B B W
W W W
W W W
B B B
Becomes
B B G
G G G
G G... |
a8bf12397726bc7b408c7dd7b91de3ee86cf8fe7 | OneWinged-Eagle/MyDailyCodingProblem | /Medium/#26/main.py | 1,949 | 3.578125 | 4 | """
Given a singly linked list and an integer k, remove the kth last element from the list. k is guaranteed to be smaller than the length of the list.
The list is very long, so making more than one pass is prohibitively expensive.
Do this in constant space and in one pass.
"""
from __future__ import annotations
from... |
ab18f2a9036fe3ee92cf95e78b0c3dd5621a85f7 | OneWinged-Eagle/MyDailyCodingProblem | /Easy/#81/main.py | 871 | 4.34375 | 4 | """
Given a mapping of digits to letters (as in a phone number), and a digit string, return all possible letters the number could represent. You can assume each valid number in the mapping is a single digit.
For example if {“2”: [“a”, “b”, “c”], 3: [“d”, “e”, “f”], …} then “23” should return [“ad”, “ae”, “af”, “bd”, “... |
f4811b7808599a57815ff0ffd55b116b394616a0 | OneWinged-Eagle/MyDailyCodingProblem | /Medium/#44/main.py | 1,478 | 4.125 | 4 | """
We can determine how "out of order" an array A is by counting the number of inversions it has. Two elements A[i] and A[j] form an inversion if A[i] > A[j] but i < j. That is, a smaller element appears after a larger element.
Given an array, count the number of inversions it has. Do this faster than O(N^2) time.
Y... |
9686900ca6bd222853802d1171215283b8d1505a | OneWinged-Eagle/MyDailyCodingProblem | /Medium/#148/main.py | 710 | 4.1875 | 4 | """
Gray code is a binary code where each successive value differ in only one bit, as well as when wrapping around. Gray code is common in hardware so that we don't see temporary spurious values during transitions.
Given a number of bits n, generate a possible gray code for it.
For example, for n = 2, one gray code w... |
e8bd01f4061e584f9ea87bc0f1b6cf1ca50fe432 | OneWinged-Eagle/MyDailyCodingProblem | /Easy/#134/main.py | 974 | 3.703125 | 4 | """
You have a large array with most of the elements as zero.
Use a more space-efficient data structure, SparseArray, that implements the same interface:
init(arr, size): initialize with the original large array and size.
set(i, val): updates index at i with val.
get(i): gets the value at index i.
"""
fr... |
d7ff6d2e27c29fd7098595653b809bf7723d5883 | OneWinged-Eagle/MyDailyCodingProblem | /Easy/#96/main.py | 487 | 4.21875 | 4 | """
Given a number in the form of a list of digits, return all possible permutations.
For example, given [1,2,3], return [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]].
"""
from typing import Any, List
def permutations(arr: List[Any]) -> List[List[Any]]:
if not arr:
return [[]]
perm = []
for i, elem in en... |
567cc537639865cb2afdae5c840774b007bc1268 | OneWinged-Eagle/MyDailyCodingProblem | /Easy/#325/main.py | 1,710 | 4.25 | 4 | """
The United States uses the imperial system of weights and measures, which means that there are many different, seemingly arbitrary units to measure distance. There are 12 inches in a foot, 3 feet in a yard, 22 yards in a chain, and so on.
Create a data structure that can efficiently convert a certain quantity of o... |
20ba12de13d458540b593833c8dfcb989f5e4168 | OneWinged-Eagle/MyDailyCodingProblem | /Easy/#282/main.py | 616 | 4.09375 | 4 | """
Given an array of integers, determine whether it contains a Pythagorean triplet. Recall that a Pythogorean triplet (a, b, c) is defined by the equation a2+ b2= c2.
"""
from typing import List
def pythagorean(array: List[int]) -> bool:
squares = set([x**2 for x in array])
print(squares)
for n in squares:
s ... |
edd6d2105e2d15c2709706a8cff345eec6a1ba8a | OneWinged-Eagle/MyDailyCodingProblem | /Medium/#51/main.py | 839 | 4.125 | 4 | """
Given a function that generates perfectly random numbers between 1 and k (inclusive), where k is an input, write a function that shuffles a deck of cards represented as an array using only swaps.
It should run in O(N) time.
Hint: Make sure each one of the 52! permutations of the deck is equally likely.
"""
from ... |
0ab34710bcb6bf8fbea9f862521afbe1c8ae6f3c | OneWinged-Eagle/MyDailyCodingProblem | /Easy/#45/main.py | 688 | 4.0625 | 4 | """
Using a function rand5() that returns an integer from 1 to 5 (inclusive) with uniform probability, implement a function rand7() that returns an integer from 1 to 7 (inclusive).
"""
from random import randrange
def rand5() -> int:
return randrange(1, 6)
def rand7() -> int:
target = 5 * rand5() + rand5()
retu... |
6fc083078fa0fd7d4fd5df3d91dc87c3cc26405b | OneWinged-Eagle/MyDailyCodingProblem | /Easy/#157/main.py | 682 | 4.375 | 4 | """
Given a string, determine whether any permutation of it is a palindrome.
For example, carrace should return true, since it can be rearranged to form racecar, which is a palindrome. daily should return false, since there's no rearrangement that can form a palindrome.
"""
def permPalindrome(string: str) -> bool:
... |
2e5093880424dc90c7dcfa2d9431415d2b4331ad | OneWinged-Eagle/MyDailyCodingProblem | /Easy/#159/main.py | 415 | 4.03125 | 4 | """
Given a string, return the first recurring character in it, or null if there is no recurring character.
For example, given the string "acbbac", return "b". Given the string "abcdef", return null.
"""
def firstRec(string: str) -> str:
s = set()
for c in string:
if c in s:
return c
else:
s.add(c)
re... |
f979f0ed6ed342cd198c04683b8f64a6968601f8 | OneWinged-Eagle/MyDailyCodingProblem | /Medium/#15/main.py | 1,339 | 3.5625 | 4 | """
Given a stream of elements too large to store in memory, pick a random element from the stream with uniform probability.
"""
from random import randrange
from typing import Any, Iterable, List
# with n = len(stream): time O(n), space O(k)
def reservoirSampling(stream: Iterable[Any], k: int) -> List[Any]:
reserv... |
3ef0c78f3b077e4a2c0d40e229e3c20c24899256 | OneWinged-Eagle/MyDailyCodingProblem | /Hard/#64/main.py | 1,174 | 3.890625 | 4 | """
A knight's tour is a sequence of moves by a knight on a chessboard such that all squares are visited once.
Given N, write a function to return the number of knight's tours on an N by N chessboard.
"""
import numpy as np
from typing import Tuple
possibleMoves = [(2, 1), (-2, 1), (2, -1), (-2, -1), (1, 2), (-1, 2)... |
159cdb83f7674b012d2874d3230b48bb9c4ab1b6 | OneWinged-Eagle/MyDailyCodingProblem | /Easy/#27/main.py | 846 | 4.34375 | 4 | """
Given a string of round, curly, and square open and closing brackets, return whether the brackets are balanced (well-formed).
For example, given the string "([])[]({})", you should return true.
Given the string "([)]" or "((()", you should return false.
"""
openBrackets = {"(": 0, "{": 1, "[": 2}
closeBrackets =... |
dec4b903270a8418fd48a80d3f7817548d97ad40 | creative-singh/MyPythonCodes | /queueLinkedList.py | 1,466 | 4.21875 | 4 | # Challenge - Implement Queue Using a linked list
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Queue:
def __init__(self):
self.front = None
self.rear = None
def enqueue(self, data):
newNode = Node(data)
if self.rear == None:
self.front = newNode
... |
b5ffc42954278f28a55599b8a0a2df1aeabc02a8 | creative-singh/MyPythonCodes | /sorting.py | 449 | 3.671875 | 4 | def counting_sort(arr):
maximum = max(arr) + 1
count_arr = [0] * maximum
sort_arr = [0] * len(arr)
for i in arr:
count_arr[i] += 1
for i in range(1, maximum):
count_arr[i] += count_arr[i-1]
for i in arr:
index = count_arr[i]-1
sort_arr[index] = i
count... |
9b41cdff1a435e0f37f55deeceb6a2d9abf6aac1 | creative-singh/MyPythonCodes | /startEndPos.py | 969 | 3.734375 | 4 | # Given a sorted array of integers A(0 based index) of size N, find the starting and ending position of a given integer B in array A.
# Your algorithm runtime complexity must be in the order of O(log n). Return an array of size 2, such that first element = starting position of B in A and second element = ending positio... |
045e2b9a0c84fa7fd632ecf9871be472759e0102 | creative-singh/MyPythonCodes | /divisibleBy.py | 285 | 4.0625 | 4 | #Challenge - Using range and for loop, print all multiples of 5, 7, 11 from 1 to 1001
for i in range(1, 1001):
if i % 5 == 0 :
print(f"Divisible by {i} ")
if i % 7 == 0 :
print(f"Divisible by {i} ")
if i % 11 == 0 :
print(f"Divisible by {i} ")
|
d661e364c2f00701594b8e6e14f8bb7b46768f80 | creative-singh/MyPythonCodes | /GradeSystem.py | 966 | 4.21875 | 4 | #Challenge :
# Write a program that takes input from the user as marks in 5 subjects and assigns a grade according to the following rules:
# Perc = (s1+s2+s3+s4+s5)/5.
# A, if Perc is 90 or more
# B, if Perc is between 70 and 90(not equal to 90)
# C, if Perc is between 50 and 70(not equal to 90)
# D, if Perc is between... |
f1ec77db8a85754daf9aa6722badaeac1026e67f | creative-singh/MyPythonCodes | /inversion.py | 262 | 3.53125 | 4 | def inversion(myList, n):
count = 0
for i in range(n):
for j in range(i + 1, n):
if (myList[i] > myList[j]):
count += 1
return count
myList = [1, 20, 6, 4, 5]
n = len(myList)
print(inversion(myList, n)) |
2b90790a74af0902e155aa8fe5009a71793cb247 | JonsSpaghetti/algorithms | /Stack/binary.py | 352 | 3.90625 | 4 | import Stack
def convToBinary(num):
s = Stack.Stack()
div = int(num)
out = ""
while div > 0:
s.push(int(div % 2))
div = int(div) // 2
for i in range(0, s.size()):
out += str(s.pop())
return out
def main():
num = input("Input a number to convert to binary: ")
p... |
406b1f38f5a3108e9f36a8fe175a3f86a1a8dcda | katiayx/coding_challenges | /coin_change.py | 1,781 | 4.0625 | 4 | """give amount, and a list of denominations, write
a function that computes the number of ways to
make amount of money using coins in available denominations"""
# example:
# a = 15
# coins = [1,3,5]
# pseudo code:
# 1. create a list: [0,0,0,0...0] - index=amount, value=ways
# 2. iterate starting with first co... |
f714ee61db7d9b0cd5de563e4c9f7a4a37714d8e | uda-desigh-program/design-of-computer-program | /Lesson3/n_ary.py | 833 | 3.9375 | 4 | from functools import update_wrapper
def decorator(d):
"Make function d a decorator: d wraps a function fn."
def _d(fn):
return update_wrapper(d(fn), fn)
update_wrapper(_d, d)
return _d
"""
# also work
def decorator(d):
return lambda fn: update_wrapper(d(fn), fn)
decorator = decorator(deco... |
2e4e566ecbf35ea3520ce9389a68bfe9e35beb1a | uda-desigh-program/design-of-computer-program | /Lesson5/play_pig.py | 8,487 | 4.09375 | 4 | # -----------------
# User Instructions
#
# States are represented as a tuple of (p, me, you, pending) where
# p: an int, 0 or 1, indicating which player's turn it is.
# me: an int, the player-to-move's current score
# you: an int, the other player's current score.
# pending: an int, the number of points... |
aa150e468eb0a78bee180473237434c85e95a893 | neenjaw/udemy-python-mega-course | /s03/lecture70.py | 458 | 3.71875 | 4 | tempertures = [10, -20, -289, 100]
def c_to_f(c):
if c < -273.15:
return "That temperature is out of range (input is less than -273.15)"
else:
f = c * 9/5 + 32
return f
with open("conversions.txt", "w") as output_file:
for temperture in tempertures:
converted = c_to_f(tempe... |
00e3c5ca8a8dfe88eb108481ab035d598ed8083b | neenjaw/udemy-python-mega-course | /s13/bookstore_gui.py | 5,980 | 3.609375 | 4 | """
An application to manage a bookstore repository
"""
from tkinter import *
from tkinter import ttk
from tkinter import font
class BookWindow():
def __init__(self, parent):
self.parent = parent
"""
The upper book area
"""
self.book_frame_style = ttk.Style()
self... |
c6145dad615c9229203149a797ae7a73d5c4ac01 | ITguyRy/py | /11-check-primality-functions.py | 339 | 4.0625 | 4 |
def num_input():
num = int(input('Give me a number to check if it is prime:\n'))
return num
def check(num):
if (num % 2 != 0):
print('that number is a prime number')
else:
print('that number is not a prime number')
def __main__():
num = num_input()
check(num)
... |
e3cf30a2c1f055c22333dcc165455e424f1d55a7 | ITguyRy/py | /1-char-output.py | 251 | 3.828125 | 4 |
year = int(input("What year is it now? \n"))
n = int(input("what is your age? I'll tell u when you'll hit 100 \n"))
age = 100 - n
future = year + age
print("you'll hit 100 in " + str(age) + " years!\nThe year will be " + str(future) + "!")
|
5e3d44517acbb19231f46eb1ca65e4e3d0f10722 | sandance/Optimization | /knapsack/solver.py | 4,415 | 3.75 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from collections import namedtuple
import os
import sys
import collections
import functools
Item = namedtuple("Item", ['index', 'value', 'weight'])
class memoized(object):
'''Decorator. Caches a function's return value each time it is called.
If called later with the s... |
3275314c4b2094daf4111f33418acc516dba9c7c | joeyemerson/Engineer-Man-Challenges | /med_fibonacci.py | 516 | 3.796875 | 4 | import sys
#starting number in sequence
value1 = '21'
#calculate value2 digits of sequence
value2 = '40'
# write your solution here
def fib(x,y):
fib_sequence = ''
counter = 0
a, b = 0, 1
while counter < y:
if a == x:
fib_sequence += f'{b}'
counter += 1... |
69be9c3fcdd9d3fd981b98c70ab63429be767b5c | pkrzyszowski/address-book | /contacts.py | 4,065 | 3.78125 | 4 | # -*- coding: utf-8 -*-
import sqlite3
import csv
import re
con = sqlite3.connect('dbtest.db')
con.text_factory = str
def create_table():
with con:
cur = con.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS Address_book(id INTEGER PRIMARY KEY AUTOINCREMENT, FirstName TEXT, Surname TEXT, Address ... |
1d127c1bb7c79d6b206c3ff398e03193743080d5 | gianmachella/Practicas-Python | /Ejercicios1.py | 2,141 | 3.5625 | 4 | #Ejercicio 1
def devolver_longitud_de_un_nombre(unNombre):
return len(unNombre)
devolver_longitud_de_un_nombre('Gian')
#Ejercicio 2
def devolver_primer_elemento_de_la_lista(unaLista):
return unaLista[0]
devolver_primer_elemento_de_la_lista(['Gian', 'Franco', 'Machella'])
#Ejercicio 3
def devolver... |
95e28308a9dec1d58e4219bf394e744d70377800 | varun-varghese/coding-practice | /interview/trees/min_heap_practice.py | 1,229 | 3.796875 | 4 | class MinHeap():
def __init__(self):
self.heap = [0]
self.size = 0
def insert(self,val):
self.heap.append(val)
self.count += 1
i = self.size
self.percUp(i)
def percUp(self,i):
while i/2 > 0: #while the parent of the node is at least root
if... |
27629acddbd11fcc15c84638b55d4c93fb7fc2aa | varun-varghese/coding-practice | /interview/dp/RodCut.py | 966 | 3.875 | 4 |
import sys
''' Given a rod of length n and array of prices for each length smaller than n,
determine the maximum value you can get with a rod by cutting the rod into
smaller pieces and selling the pieces.
Example: Length: 1 2 3 4 5 6
Prices: 6 5 3 3 1 1
The best price is to sel... |
ee6db528a5b96eee6f3dcc705b7884a71d7faf3d | varun-varghese/coding-practice | /interview/strings/inttostring.py | 1,166 | 4.21875 | 4 |
def int_to_string1(num):
"""Naive implementation with O(n) string concatenation for a total complexity of O(n^2)"""
nums = ["0","1","2","3","4","5","6","7","8","9"]
res = ""
while num > 0:
digit = num % 10
num /= 10
res = nums[digit] + res
return res
def int_to_string2(num):
"""Using char array for join... |
a506c77861564c8fd4bc77f3dbc3661faddbb3af | varun-varghese/coding-practice | /interview/dp/subsetSums.py | 893 | 3.578125 | 4 |
def subsetSum(nums,i,k):
''' Runs in O(2^n) '''
if k == 0:
return True
if i == 0:
return False
# include ith element and not include ith element
return subsetSum(nums,i-1,k-nums[i]) or subsetSum(nums,i-1,k)
def subsetSumDP(nums,k):
''' Runs in O(kN) time and space '''
n = len(nums)
sol = [[0 for _ in ra... |
4fecd97f4a93ba91413c585143e1c5be517fbdff | gaijinctfx/PythonExercicios | /EstruturaDeRepeticao/estruturaderepeticao-02.py | 1,125 | 4.0625 | 4 | # author: ZumbiPy
# E-mail: zumbipy@gmail.com
# Exercicio do site http://wiki.python.org.br/EstruturaDeRepeticao
"""
2 - Faça um programa que leia um nome de usuário e a sua senha e não aceite a
senha igual ao nome do usuário, mostrando uma mensagem de erro e voltando a
pedir as informações.
"""
# =====================... |
2bf8fabd5861633e387a7c4d49b4da6987df3037 | gaijinctfx/PythonExercicios | /Estrutura_De_Decisao/estruturadedecisao-20.py | 1,503 | 3.765625 | 4 | # author: ZumbiPy
# E-mail: zumbipy@gmail.com
# Exercicio do site http://wiki.python.org.br/EstruturaDeDecisao
# Para execurta o programa on line entra no link a baixo:
# https://repl.it/I207/1
"""
20 - Faça um Programa para leitura de três notas parciais de um aluno.
O programa deve calcular a média alcançada por alun... |
64dbc6a1c55d6d975b718184b2dac5addba130cc | oybektoirov/Project-Euler | /P7_10001st_prime.py | 404 | 3.765625 | 4 | def n_prime(limit):
num = 7
prime_list = [2, 3, 5]
while True:
if is_prime(num, prime_list):
prime_list.append(num)
if len(prime_list) == limit:
return prime_list[-1]
num += 2
def is_prime(num, prime_list):
for i in prime_list:
... |
1cb98341bc9761d54797d5f7fea2d0772b5e9b77 | KayeARK/Evolutionary-Game-Theory | /Mixed Strategy/Mixed Strategy Realistic Environment.py | 4,030 | 3.71875 | 4 | import matplotlib.pyplot as plt
import random
#0 is the dove strategy
#1 is the hawk strategy
#getting 1 food allows survival, getting 2 food allows replication
#p/q<1 food is p/q chance of surviving
#1+p/q>1 food is p/q chance of replicating
population=[0.5] #array of individuals, with either hawk or dove strategy,... |
c7ebb2c943a1d063571e3028d25435eba3c38e0b | SherbazHashmi/HackathonServer | /arcpyenv/arcgispro-py3-clone/Lib/site-packages/arcgis/geoanalytics/use_proximity.py | 4,966 | 3.609375 | 4 | """
These tools help answer one of the most common questions posed in spatial analysis: What is near what?
create_buffers() creates areas of a specified distance from features.
"""
import json as _json
import logging as _logging
import arcgis as _arcgis
from arcgis.features import FeatureSet as _FeatureSet, ... |
a95b53996a55e638097ae0960f7dbbe774232544 | SherbazHashmi/HackathonServer | /arcpyenv/arcgispro-py3-clone/Lib/site-packages/arcgis/geoprocessing/_types.py | 6,192 | 4.03125 | 4 | import json
import tempfile
class LinearUnit(object):
"""
A data object containing a linear distance, used as input to some Geoprocessing tools
================ ========================================================
**Argument** **Description**
---------------- ----... |
221739a54d050e7ca7b584645e1f748811b7b302 | michaelsizonenko/ratebot | /test_main_bot.py | 2,795 | 3.65625 | 4 | import unittest
from main import *
class CalcTest(unittest.TestCase):
"""rate bot tests"""
@classmethod
def setUpClass(cls):
print("==========")
def test_get_history_url(self):
self.assertIsNone(get_history_url(10, 'not_valid_currency'))
self.assertTrue(get_history_url(1000, ... |
a3cdc82029378bed72e9ffd1fbdd2207ea1101a9 | kmartin62/AI_Repo | /AI/Uninformal/Pacman1.py | 5,229 | 3.765625 | 4 | from AI.uninformed_search import *
def move_right(x, y, obstacles):
if x < 9 and [x + 1, y] not in obstacles:
x += 1
return x
def move_left(x, y, obstacles):
if x > 0 and [x - 1, y] not in obstacles:
x -= 1
return x
def move_up(x, y, obstacles):
if y < 9 and [x, y + 1] not in obst... |
2927ecf4d1d50234c872853d0c93df428cb23a84 | JKakaofanatiker/pw | /pw.py | 551 | 3.59375 | 4 | import secrets
import string
from colorama import Fore # needed for color
import pyperclip
print(Fore.GREEN + "Enter password length:") # tell the user to type the length of the password
length = input() # user input
length = int(length)
chars = string.digits + string.ascii_letters + string.punctuation # possible char... |
2182839c34a3c911ffe158c62d187610ad50802e | Shymwo/gomoku_websocket | /gomoku-server/game.py | 4,899 | 3.5625 | 4 | import math
class Game:
WHITE = "O"
BLACK = "X"
def __init__(self, name, player1):
self.name = name
self.white = player1
self.black = None
self.white.game = self
self.white.color = Game.WHITE
self.white.write_message({
'answer' : 'waiting',
})
self.turn = Game.WHITE
self.boardSize = 15
sel... |
867b9cfdac4e76e53f1235ee19e82f17d40a84bb | bdomash/Python_For_Fun | /GPA.py | 1,098 | 3.546875 | 4 | '''
Created on Apr 2, 2016
@author: Brandon
'''
classes = {"SAS":3,"Machine Learning":3,"Stat Design":3,"Directed Study":3}
gpaValues = {"A":4.0,"AB":3.5,"B":3.0,"BC":2.5,"C":2.0}
springGPA = {"SAS":"A","Machine Learning":"A","Stat Design":"A","Directed Study":"A"}
currentGPA = [370.0/99.0,99.0]#[3.39,13] #[GPA,cre... |
823304839a2adbaadf2869d7497e2e73c4a6cf3c | lemieux/mediaplayer | /player.py | 7,333 | 3.6875 | 4 | import os
import sys
import pygame
pygame.init()
class MediaPlayer:
def __init__(self, path):
self.base_path = os.path.abspath(path)
self.current_path = self.base_path
self.paused = False
def start(self):
self.prompt_menu()
def prompt_menu(self):
self.directories ... |
fada8b6897945e6eb42e396926c48a452342e5b8 | HundenOdin/newRepo | /list.py | 1,331 | 3.8125 | 4 | import sys
grades = []
def detString(countString):
if countString[-1] == "1" and len(countString) == 1:
a = raw_input("Please enter the %sst grade.\n" % (countString))
grades.append(float(a))
elif countString[-1] == "1" and not countString[-2] == "1" and len(countString)>1:
a = raw... |
bec81b9e36467f9b614f35b07d7caeb666e4c655 | DanikKaragodin/python | /MyQueue.py | 1,156 | 3.859375 | 4 | class MyQueue:
stack1=[]
stack2=[]
def __init__(self):
self.MyQueue=[self.stack1,self.stack2]
def pushInStackOne(self,x):
self.stack1.append(x)
return self.stack1[-1]
def pushInStackTwo(self,x):
self.stack2.append(x)
return self.stack2[-1]
def p... |
a6cddf10f18b7c8878c4f00d475e7c21791a1155 | DanikKaragodin/python | /Homework24.04.21/algorithm.py | 2,096 | 3.890625 | 4 | # Дано
# 1.Есть два числа и знак,которые вводятся пользователем
# 2.Программа зациклена
# 3.Завершение программы на знак '0'
# 4.Введение неверного знака приводит к ошибке и повторному запросу
# 5.Сообщение о невозможности деления на 0(нуль)
# Задачи
# 1. правильный input
# 2. программу зациклить под while
#... |
e842f121a559786bd0cd190f10cb34ccde7518f0 | DanikKaragodin/python | /Untitled-1.py | 753 | 4.15625 | 4 | import time
#Первое задание
print("Первое задание:")
print("Silence is golden")
time.sleep(1)
#Второе задание
print("Второе задание:")
print("Введите два числа:")
a= int(input())
b=int(input())
print(a, "+", b, "=", a+b)
print(a, "*", b, "=", a*b)
time.sleep(1)
#Третее задание
print("Третее задание:")
p... |
34a4e5c4d21b403832ff0e58ca73efd69ccad88b | CurtCodes/python_winter2020 | /wk1/Day2/Functions.py | 1,483 | 4.15625 | 4 | # # Define f(x)=x+1
# def f(x):
# ans=x+1
# return ans
# my_sol=f(1)
# print(my_sol)
# def g(y):
# eq1=y**4 + y**2 + 1
# return eq1
# sol2=g(2)
# print(sol2)
# Functions with multiple returns
# def get_first_two_evens():
# return 2, 4
# even1, even2 = get_first_two_evens()
# print(even1)
# pr... |
19a8fe145b59369462412cbe1c7fd640dacffe91 | CurtCodes/python_winter2020 | /wk1/Day1/conditionals.py | 223 | 4.09375 | 4 | number=int(input('Enter a number: '))
min_num=3
max_num=15
if number>min_num and number<max_num:
print('nooice')
elif number>min_num - 2 and number < max_num + 2:
print('ehh, you pass')
else:
print('not nooice') |
55e0b62474f4e3058ad94a4cc6832f2f2bd3011a | CurtCodes/python_winter2020 | /wk1/Day1/operators.py | 170 | 4 | 4 | string1='hello'
string2=' King'
string3=string1 + string2
print(string3)
string1='hello'
int1=5
string2=str(int1)
print(string1+string2)
#modulo operator
print(18%5) |
e8b5cf2267e2b854344dbfeb54ad59a99c18aecf | NikolajX4000/exercism.io | /python/word-count/word_count.py | 255 | 3.65625 | 4 | from collections import Counter
import re
def count_words(sentence):
sentence = sentence.lower()
words = re.split(r"[^a-z0-9']", sentence)
words = [x.lstrip("'").rstrip("'") for x in words if x != '']
return dict(Counter(words).items())
|
3bd1e11a0eafb89b668ee96cfe982d44eacf7265 | pavdemesh/learning_python | /queues_protected_list.py | 694 | 4.15625 | 4 | """
Implement queue as a list.
Protect from mutation via encapsulation
"""
class Queue:
def __init__(self, starting_queue=[]):
self.__queue_list = list()
for item in starting_queue:
self.__queue_list.append(item)
def enqueue(self, value):
self.__queue_list.append(value)
... |
2c38532295f9ea995679688538c649cb73942549 | pavdemesh/learning_python | /queue_and_stack.py | 312 | 3.84375 | 4 | stack = list()
stack.append("p")
stack.append("a")
stack.append("s")
stack.append("h")
last_char = stack.pop()
print(last_char)
print(stack)
queue = list()
queue.append('banana')
queue.append('grapes')
queue.append('mango')
queue.append('orange')
first_element = queue.pop(0)
print(first_element)
print(queue)
|
45873de7f70c16dae89053c8f8c62aa625ddb616 | pjconsidine/codingclass | /triangle.py | 1,155 | 4.1875 | 4 | # -*- coding: utf-8 -*-
import math
def area(base, height):
''' (number, number) -> number
returns the area of a triangle with given base and height
'''
return base * height / 2
def perimeter(side1, side2, side3):
'''(number, number, number) -> number
Returns the perimeter o... |
ae8818b65b56b274dd53fc465030e4ea197921fe | mikemartin8/20776.-055--python-for-beginners | /homework/homework-5/homework_2_upgrade.py | 2,269 | 4.46875 | 4 | ## Michael Martin
## 1/31/2017
## Homework #2
## Create the function "AskForLetter():" such that the function repeatedly
## asks the user for a single letter until the user types "quit" to exit the
## program or they have entered a vowel. Use the python function "len" to call
## a second function called "IsVowel(lette... |
f062fb59f6aaadcb99f4eec416b6bb433ddf7e1f | mikemartin8/20776.-055--python-for-beginners | /lecture-examples/lab_9_exercises_num_1_thru_4.py | 2,395 | 3.984375 | 4 | '''
lab_9_exercises_num_1_thru_4.py - Shows how to read and write files (file I/O)
'''
def PrintLinesInFile(filename):
try:
file = open(filename)
except IOError:
print 'File cannot be found!'
else:
for line in file:
print line
file.close()
def CreateNewFile(fil... |
4acb3995e14ace56dd60c2c57a475380a80a25be | Rishi-Kumar-coder/First | /clockk.py | 309 | 3.75 | 4 | import turtle
#defining turtle and screen
pen = turtle.Turtle()
sr = turtle.Screen()
a = 10
def pin_1():
pen.forward(100)
a = a+10
pen.forward(100)
def pin_2():
pen.forward(100)
a = a - 10
pen.forward(100)
sr.onkey(pin_1, "Left")
sr.onkey(pin_2, "Right")
input() |
c90b9a515e173f19c5c6f7c072bfd40210ff0657 | tgf90/tgf90 | /RockPaperScissors1.py | 2,544 | 4.40625 | 4 | """
What if you wanted a game of Rock, Paper, Scissors where you have a score? And plays on a loop and
can play if Rock Paper or Scissor are capitalized or are lowercase and checks
if you input a valid response and not random characters. What if I add more to this and make this
a more complex game.
"""
import random
i... |
a779ae206bd5c5e7de623c7b7a16b1b521747a9f | nagagopi19/Python-programms | /assertstatement.py | 389 | 4.15625 | 4 | # assert Statements
# User should enter a number between 100 and 200
'''num = int(input('Enter a number(100-200):'))
assert num>=100 and num<=200,"Invalid input entered"
print("You entered:", num)'''
try:
num = int(input('Enter a number(100-200):'))
assert num>=100 and num<=200,"Invalid input entered"
p... |
86be46185931b33e383a99fb786e1fc076fca3f9 | nagagopi19/Python-programms | /floatnumberfromkeyboard.py | 104 | 3.890625 | 4 | # To accept a float number from keyboard
num = float(input('Enter a float:'))
print('U entered= ', num)
|
ec095ff68aabac1d5db94af0dda4d9e293fd3de3 | nagagopi19/Python-programms | /forloop.py | 1,539 | 4.21875 | 4 | '''# to disply nos from 1 to 10
#obj = range(1,11)
#for i in obj:
for i in range(1,11):
#print(i)
print(i, end='\t')
#print(i,end=' ')'''
# to display even nos for 10 to 20
'''for i in range(10,21,2):
# if i % 2=0
print(i, end='\t')'''
'''# To retrive even from a given list of nos
mylst=[10,11,12,... |
398aa7a56ade1708aacc75b2b7a5692da7b64421 | nagagopi19/Python-programms | /breakstatement.py | 169 | 3.96875 | 4 | # Break statement
# To display nos from 1 to 10
x = 1
while x<=10:
print(x)
if x>5: break
#if x>=5: break
x+=1 #x=x+1
print('Out of while')
|
23e82efa34cb54df693c9ab30054264d6fa71275 | nagagopi19/Python-programms | /Listappend.py | 192 | 3.828125 | 4 | '''x = int(input("Enter a list:"))
list = []
x.append(list)
print(list)'''
x=[1,2,3,4,5,6,7,8,9,10]
even_numbers= list(filter(lambda y: y%2 == 0, x))
print(even_numbers)
|
7796a8d700d6fb4f25680fa8d32968ebe9b557f1 | nagagopi19/Python-programms | /single char from keyboard.py | 99 | 3.578125 | 4 | # To accept a single char from keyboard
str = input('Enter a char: ')
print('U entered= ', str[0])
|
cc05f04ca88c70c54b5bf468893d3d4d0cd1cfd7 | nagagopi19/Python-programms | /ifstatemnetdemo.py | 103 | 4.03125 | 4 | #if demo
str = 'Hello1'
if str == "Hello":
print("Yes it is Hello")
print("Done")
print('End')
|
c221528fa58e073ad9f7b942dd504ec35eda1248 | lliga1/CIS_2348 | /Homework2/lab7.25.1.py | 1,648 | 3.625 | 4 | #Marianel Liga
#CIS 2348
#Lab 7.25.1
#Student ID: 1394330
def exact_change(user_total):
if (user_total <= 0):
return None
else:
num_dollars = user_total // 100
user_total %= 100
num_quarters = user_total // 25
user_total %= 25
num_dimes = user_total // 10
... |
88a1c94a36ef952234d33c3623e981039be47cfd | lliga1/CIS_2348 | /Homework4/Zylab_12.7.py | 888 | 3.96875 | 4 | # Marianel Liga
# PSID 1394330
# Homework 12.7
def get_age(): # function to read age from inputs
age = int(input())
if age < 18 or age > 75: # check age validity
raise ValueError("Invalid age.") # If age is not valid, raise exception
return age # If age is valid, return age
def fat_burning_h... |
5e6d03ea22b7929467006d71cb80451e654d41ce | annamid/beroepsopdracht | /helloyou.py | 120 | 3.703125 | 4 | print("Hello You!, ik ben Anna")
print("wie ben jij")
naam = input("Enter username:")
print("Username is: " + naam)
|
73f2b3798acca75603cbb22d7d25ab121aa856fa | juliosimply/Aulas-Python-Guanabara | /Exercicio001-007.py | 1,312 | 4.125 | 4 | #Exercício 001
#print('olá mundo!')
#Exercicio 002
#nome = input("qual o seu nome?")
#print(' Muito prazer', nome, 'seja muito Bem vindo')
#Exercicio 003
# n1 = int (input('Digite un número:'))
# n2 = int (input('Digite outro numero:'))
#s = n1 + n2
#print('a soma de {} + {} é {}'.format(n1, n2, s))
#Exercício 00... |
f5282fbdaa608024ada0d1aecfc2451a5204a83e | juliosimply/Aulas-Python-Guanabara | /Exercicio 025.py | 173 | 3.78125 | 4 | #Exercicio 025 procurando uma string dentro de outra
nome = str(input('Digite seu nome completo')).strip()
print('tem silva no seu nome?{}'.format('silva' in nome.lower()))
|
0a9687ab56d1c73dbf099cc31d0ff64184049a34 | juliosimply/Aulas-Python-Guanabara | /Exercicio 081 (extraindo dados de uma lista).py | 389 | 4 | 4 | num = []
resp = 's'
while True:
n = int(input('Digite um valor'))
num.append(n)
resp = str(input('Quer continuar [S/N]?'))
if resp in 'nN':
break
num.sort(reverse=True)
print(f'foram digitados {len(num)}')
print(f' os numeros digitados foram: {num} elementos')
if 5 in num:
print('o numero 5 ... |
d61b50a96c3121a0d3a448b50d9192246ce75b27 | juliosimply/Aulas-Python-Guanabara | /Exercicio 072.py | 450 | 4.03125 | 4 | nExtenso = ('zero', 'Um', 'Dois', ' Três', 'Quatro', 'Cinco', ' Seis', 'Sete', 'Oito',
' NOve', 'Dez', 'Onze', ' Doze', 'Treze', 'Quatorze', ' Quinze', 'Dezesseis', 'Dezessete',
'dezoito', 'Dezenove', 'Vinte')
while True:
num = int(input('Digite um numero de 0 a 20:'))
if num > 20 or nu... |
5c9837fa16eadf738f6e9828a42e1e87944e12e7 | jil945/genetic-algorithm | /selection.py | 1,946 | 3.5625 | 4 | import random
def selection_elite(fitness, population, **kargs):
scored_pop = sorted(population, key=fitness, reverse=True)
selection = int((.1 * len(population)))
res = scored_pop[:selection]
random.shuffle(res)
return res
def selection_best_half(fitness, population, **kargs):
scored_po... |
50959f2d64c1eccf6a4c467be8e2c9d5f15346ef | Andre-Pham/Information-Visualiser | /read_visrep_video.py | 4,431 | 3.5 | 4 | # Code to generate text from visual representation video (webcam)
# Import modules
import cv2
from threading import Thread
# Import complimenting scripts
from read_visrep_photo import *
from constants import *
def read_visrep_video():
'''
Both reads and displays video from the webcam simultaneously, by runnin... |
a55654f83ec4643be93f3591cd02d177483db241 | GitGudJonas/Public | /Sort_Characters_by_Frequency.py | 886 | 3.8125 | 4 | ############ Aestheticc enter #########
#import numpy as np
from collections import Counter
#######################################
class Solution:
def frequencySort(self, s: str) -> str:
u = Counter(s).most_common()
w=""
for letter,count in u:
w+=(letter*count)
... |
2f0de43bb6ce63ecd75d2255b0a0540a22b5ed83 | GitGudJonas/Public | /Climbing_Stairs.py | 842 | 3.78125 | 4 | ############ Aestheticc enter #########
#import numpy as np
#from collections import Counter
#######################################
##Definition for a binary tree node.
class Solution:
def climbStairs(self, n: int) -> int:
a,b=1,1
for i in range(0,n):
a,b=a+b,a
retur... |
57baaae9ae69a49668c115e8a61b771c40f7baad | qahSgiB/AdventOfCode2018 | /1Simple/SolutionA/solution.py | 224 | 3.671875 | 4 | inputFile = open('input.txt', 'r')
frequenciesChange = inputFile.read().split('\n')
frequenciesChange.pop(-1)
frequency = 0
for frequencyChange in frequenciesChange:
frequency += int(frequencyChange)
print(frequency)
|
d5dcd6cb399c5f7ee2beb4f99247717608a8ea33 | clair3st/Rosalind-katas | /src/shared_motif.py | 1,006 | 3.6875 | 4 | """Find shared motif."""
from sys import argv
def longest_substring(data):
"""Loop through each character to be start of substring.
keep track of a substrings that appear in all items in list.
Update for the longest substring.
"""
longest_substr = ''
for start_idx in range(len(data[0])):
... |
33db19d82826c0552be988a871bb9afa2ee1abb3 | IanRiceDev/portflio | /allPrimes.py | 300 | 3.953125 | 4 | # prints primes to a given range
import primeclass
# imports prime class
z = 1
# defines variable and sets it equal to 1
i = 0
# defines variable and sets it equal to 0
while i < 100:
x = primeclass.check_if_prime(z)
print(x)
i += 1
z += 1
# loop to print primes to screen |
5c6a997929a94f6abe2acd4ec2fcdeb9b6972f12 | lalit97/dsa-lessons | /linked-lists/day04-nth-from-end.py | 646 | 3.9375 | 4 | """
https://practice.geeksforgeeks.org/problems/nth-node-from-end-of-linked-list/1
"""
"""
Your task is to return the data stored in
the nth end from end of linked list.
"""
"""
can be done by either of the 3 methods
-> Brute Force simple traversal (length nikal sakte hain) (done)
-> 2 pointers(not runner up techniq... |
312311caeda66b87f1f81be096d8c6169dbc1331 | lalit97/dsa-lessons | /array-strings-map/day05-transition-point.py | 712 | 4.03125 | 4 | """
(1) Problem
https://practice.geeksforgeeks.org/problems/find-transition-point-1587115620/1
(2) Example
0 0 0 1 1
3
(3) Idea
"""
"""
complete the function transitionPoint()
Your function should return transition index
"""
"""
def transitionPoint(arr, n):
length = len(lis)
for index in range(length):
item =... |
9c705cbd7c3a3a113c1daa1b00dcf34e1019ed6d | lalit97/dsa-lessons | /stack-queue/queue-imp.py | 834 | 4.03125 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Queue:
def __init__(self):
self.first = None
self.last = None
def add(self, data):
"""
add item to queue
"""
def remove(self):
"""
remove item from qu... |
0ae4ce80c21019fd8cc843545586b3a49788c7be | lalit97/dsa-lessons | /linked-lists/day02-middle-element.py | 660 | 4.0625 | 4 | """
https://practice.geeksforgeeks.org/problems/finding-middle-element-in-a-linked-list/1
"""
"""
Method -> 1 (Traversal)
def get_length(head):
count = 0
while head is not None:
count += 1
head = head.next
return count
def findMid(head):
length = get_length(head)
middle = length //... |
5fb76380652e36f1b6ba8960150ddd19b4c250de | lalit97/dsa-lessons | /linked-lists/day02-implement.py | 2,303 | 3.78125 | 4 |
#init -> initializer
"""
class Integer:
def __init__(self, data):
self.data = data
class Table:
def __init__(self, w, h, color):
self.w = w
self.h = h
self.color = color
t1 = Table(4,5,'white')
Integer -> 4
Char = 'C'
Table -> width, height, colour
(data, next)
"""
class Node:
def __init__(sel... |
10b4bd55dfa36deba113cf5343378a8f90856cf0 | emilberwald/mathematics | /mathematics/algebra/dual.py | 1,685 | 3.5 | 4 | from mathematics.number_theory.combinatorics import integer_partitions
class Dual:
def __init__(self, vector_base, result_type, i):
self.vector_base = vector_base
self.result_type = result_type
self.i = i
def __call__(self, vector_base_vector):
return self.result_type(self.vec... |
2eb4e54df7926f122febc0bc022c16b7c66d885d | Narange/Python-repo | /algs/sorting_main.py | 872 | 4.28125 | 4 | # Run the sorting functions here
import random
import sorting_algs
# Return a list of size length - each elem is random int in range given
# Ex: random_list(10, (1, 100)) -> A list of 10 random ints from 1 to 100
def random_list(length, span):
the_list = []
for i in range(length):
the_list.append(ran... |
ad4bc256652e71b0141ddf43c9d1012299b1dc69 | hexiu/hello_python | /learn_1/python4.py | 203 | 3.796875 | 4 | #-*-coding:utf-8-*-
names=['nihao','hello','hi']
for name in names:
print(name)
sum=0
for x in [1,2,3,4,5,6,7,8,9]:
#for y in x:
sum=sum+x
print(sum)
m=0
for y in range(101):
m=m+y
print(m)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.