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 |
|---|---|---|---|---|---|---|
d4638e1949299167c8580b8f61c1b0d9f5b43280 | yenjenny1010/homework | /EX04_22.py | 412 | 3.953125 | 4 | #s0951034 顏禎誼
x,y=eval(input("Enter a point with two coordinates:(seperate by comma) "))
distance=(x**2+y**2)**(1/2)#計算與原點距離
if distance<10:
print("Point (" ,x,",",y, ") is in the circle")
elif distance==10:
print("Point (" ,x,",",y, ") is on the circle")
else:
print("Point (" ,x,",",y, ") is not in the cir... |
2abf36f2f383c05c27879d59394dc2b326a31e7a | thanhtd91/proso-apps | /proso/list.py | 980 | 4.09375 | 4 | """
Utility functions for manipulation with Python lists.
"""
import proso.dict
def flatten(xxs):
"""
Take a list of lists and return list of values.
.. testsetup::
from proso.list import flatten
.. doctest::
>>> flatten([[1, 2], [3, 4]])
[1, 2, 3, 4]
"""
return [... |
70d05ab9ca90e384aaa08eb3699dc5f1e9e718de | Zokol/blackhat-python | /src/task2.py | 958 | 3.625 | 4 | import sys
import re
sample = "$8:2>9#2%2$#>90$#%>90"
def is_printable(s):
if len(set(s)) < 4:
return False
return bool(re.match('^[a-zA-Z0-9]+$', s))
#return not any(repr(ch).startswith("'\\x") or repr(ch).startswith("'\\u") for ch in s)
def testXOR(s):
for i in range(0, 255)... |
0077eae25b7f9731ffa985e5f7a8e079e417c27b | ScottBlaine/mycode | /fact/loopingch.py | 808 | 4.28125 | 4 | #!/usr/bin/env python3
farms = [{"name": "NE Farm", "agriculture": ["sheep", "cows", "pigs", "chickens", "llamas", "cats"]},
{"name": "W Farm", "agriculture": ["pigs", "chickens", "llamas"]},
{"name": "SE Farm", "agriculture": ["chickens", "carrots", "celery"]}]
Farm = farms[0]
for... |
53b199987de8d0e6982fda66e1def7226d44a1ff | ChrisMusson/Problem-Solving | /HackerRank/RegEx/0-Easy/17-alternative-matching.py | 293 | 3.59375 | 4 | '''
Given a test string, S, write a RegEx that matches S under the following conditions:
S must start with Mr., Mrs., Ms., Dr. or Er..
The rest of the string must contain only one or more English alphabetic letters (upper and lowercase).
'''
regex_pattern = r"^(Mr|Mrs|Ms|Dr|Er)\.[a-zA-Z]+$"
|
db4ad5a5c2dec491b9d50a14aaf617b2cebe5ebe | ChrisMusson/Problem-Solving | /Project Euler/032_Pandigital_products.py | 1,622 | 4 | 4 | '''
We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once;
for example, the 5-digit number, 15234, is 1 through 5 pandigital.
The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier,
and product is 1 through 9 pandigital.
Fin... |
9ac7cd01376277bb2c276880b8127768a967acf7 | ChrisMusson/Problem-Solving | /Project Euler/050_Consecutive_prime_sum.py | 1,628 | 3.84375 | 4 | '''
The prime 41, can be written as the sum of six consecutive primes:
41 = 2 + 3 + 5 + 7 + 11 + 13
This is the longest sum of consecutive primes that adds to a prime below one-hundred.
The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.
Which prime,... |
b70f2af3499fde9447ec8739f19601e97671c4c6 | ChrisMusson/Problem-Solving | /Project Euler/014_Longest_Collatz_sequence.py | 1,250 | 4.03125 | 4 | '''
The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this sequence (starting at 13 and finishing at 1) c... |
33d66808b44b182de3a9978dee9a8e88ce2d8b83 | kranthikiranm67/TestWorkshop | /question_03.py | 1,044 | 4.1875 | 4 | #question_03 =
"""
An anagram I am
Given two strings s0 and s1, return whether they are anagrams of each other. Two words are anagrams when you can rearrange one to become the other. For example, “listen” and “silent” are anagrams.
Constraints:
- Length of s0 and s1 is at most 5000.
Example 1:
Input:
s0 = “listen”
... |
c29b943b165450a4c087cb85e5b2c40c67661b8d | AlenaRyzhkova/CS50 | /pset6/sentimental/crack.py | 1,680 | 3.6875 | 4 | import sys
import crypt
def findPassword(hash, salt, guessPass):
# trying for 1-letter key
for fst in range(ord('A'), ord('z')):
guessPass=chr(fst)
tryingHash = crypt.crypt(guessPass,salt)
if tryingHash == hash:
print(guessPass)
return
# trying for 2 lett... |
26c06e9f868010768bdc7c7248cd1bf69032b1c4 | AlenaRyzhkova/CS50 | /pset6/sentimental/caesar.py | 628 | 4.21875 | 4 | from cs50 import get_string
import sys
# 1. get the key
if not len(sys.argv)==2:
print("Usage: python caesar.py <key>")
sys.exit(1)
key = int(sys.argv[1])
# 2. get plain text
plaintext = get_string("Please, enter a text for encryption: ")
print("Plaintext: " + plaintext)
# 3. encipter
ciphertext=""
for c in ... |
8820e78c180b4a61dfcd417047605a0dba15a1fe | Imonymous/Practice | /Interviews/Amazon/automata.py | 666 | 3.546875 | 4 | #!/usr/bin/env python
def exor(a, b):
if a == b:
return 0
else:
return 1
def cellCompete(states, days):
# WRITE YOUR CODE HERE
n = len(states)
if states == [0]*(n) or days <= 0:
return states
for i in range(days):
new_states = [0]*(n)
for j in range(n):... |
130ec723c0d1278ea92bf3f3f56b294f358e199c | Imonymous/Practice | /Recursion/pattern_matching.py | 1,075 | 3.5625 | 4 | #!/usr/bin/env python3
# Mock 8
def check_for_all_stars(pattern, pattern_idx):
i = pattern_idx
while i < len(pattern):
if pattern[i] != "*":
return False
i += 1
return True
def doesMatch(string, pattern):
return doesMatchRecursive(string, 0, pattern, 0)
def doesMatchRecur... |
bde17e2a75b7c65cc0ae6d0676ae7f6319f9e45f | Imonymous/Practice | /Trees/printAllPaths.py | 2,519 | 3.546875 | 4 | #!/usr/bin/env python
import sys
from collections import deque
class TreeNode():
def __init__(self, val=None, left_ptr=None, right_ptr=None):
self.val = val
self.left_ptr = left_ptr
self.right_ptr = right_ptr
class BinaryTree():
class Edge():
def __init__(self, parentNodeIndex... |
f4b77306a9d41e8bf77b05b590c73452ec2cfd4b | Imonymous/Practice | /Sorting/Mock_1.py | 1,609 | 3.96875 | 4 | #!/usr/bin/env python3
# 1st Mock - sort(arr, k) where k=max distance of an element from its original position
# Actual attempt (Selection sort)
a = [2, 3, 1, 6, 5, 4]
k = 2
# def sel_sort(arr, k):
# for i in range(len(arr)):
# min_idx = i
# for j in range(i+1, i+k+1):
# if j < len(ar... |
0047e4e9211409c8c94e9f20494f72f35f6d60e6 | itf/led-curtain-2 | /Patterns/ExtraPatterns/StatePatterns.py | 5,640 | 3.703125 | 4 | import random
import math
import colorsys
import Patterns.Pattern as P
import Patterns.StaticPatterns.basicPatterns as BP
import Patterns.Function as F
'''
State Patterns are patterns that have an internal state
'''
import Config
import random
import copy
StateCanvas = Config.Canvas
_dict_of_state_patterns={}
def ... |
53139e4c82ea5ba946ba0e1099f550855a3c054d | IvanMerejko/3-semestr | /КГ/lab3.py | 2,043 | 3.65625 | 4 | from tkinter import *
PIXEL_SIZE = 2
HEIGHT = 400
WIDTH = 400
black_rbg = 123456
dots = []
window = Tk()
# Place canvas in the window
canvas = Canvas(window, width=WIDTH, height=HEIGHT)
canvas.pack()
def is_point_in_line(point, start_line, end_line):
x, y = point[0], point[1]
x0, y0 = start_line[0], start_l... |
17e7494fcbb225659e4e6add6d0f4874fdf87f59 | dannslima/MundoPythonGuanabara | /MUNDO3/ex072.py | 561 | 4.25 | 4 | #Crie um programa que tenha uma tupla totalmente preenchida com uma contagem por extenso,
# de zero até vinte.
#Seu programa deverá ler um numero pelo teclado (entre 0 e 20) e motra-lo por extenso.
cont = ('zero','um','dois','tres','quatro','cinco','seis','sete','oito','nove','dez','onze','doze',
'treze','quatorze','q... |
8f47a65043ee96d8ef02c731343b5d103d178edf | navlalli/colour-soap-films | /src/decorators.py | 314 | 3.625 | 4 | """ Decorators """
import time
def timeit(func):
def wrapper(*args, **kwargs):
start_time = time.time()
output = func(*args, **kwargs)
end_time = time.time()
print(f"{func.__name__}() --> {end_time - start_time:.2f} s execution time")
return output
return wrapper
|
adb324d9193027da91f64735499ed88bbfb2aa9e | Manish-bit/Fresh | /birth.py | 112 | 3.5625 | 4 | birth_date = input('birth date:')
print(type(birth_date))
age = 2020-int(birth_date)
print(type(age))
print(age) |
2234fd813cf426e6d42c3ad7f61a8ab1a9a0ef45 | losskatsu/Programmers | /practice/sort/K번째수.py | 382 | 3.5 | 4 | # 100 점
def solution(array, commands):
answer = []
n = len(commands)
for i in commands:
tmp_array = []
init = i[0]-1
end = i[1]
n_ch = i[2]-1
for j in range(init, end):
tmp_array.append(array[j])
tmp_array.sort()
print(tmp_array)
a... |
654910c7c7fd36f1a9db54f53a9a57a1ee6efc93 | alggalin/PythonChess | /chess/board.py | 3,753 | 3.859375 | 4 | import pygame
from .constants import BLACK, BROWN, ROWS, SQUARE_SIZE, TAN, ROWS, COLS, WHITE
from .piece import Piece
from chess import piece
class Board:
def __init__(self):
self.board = []
self.selected_piece = None
self.create_board()
def make_queen(self, piece):
if piece.co... |
d1122b050c0cfc85ff9d7d4dcbc40c2c3096f1be | Moeozzy/Minesweeper | /Mine.py | 18,116 | 3.578125 | 4 | #Här kallar jag på olika moduler men även en python fil vilket inehåller en klass.
from tkinter import *
from tkinter import messagebox
import sys
import os
from operator import attrgetter
from Mine_Class import *
import time
import random
#Detta är fönstret som öppnas vid start av programet, I detta tkinter fönster
#... |
9290690787a3f69a48c29ff85d9c8b29a5f6caee | ehjalmar/AoC2019 | /day3part1.py | 1,779 | 3.84375 | 4 | class Coord:
def __init__(self, x, y):
self.x = int(x)
self.y = int(y)
self.distance = abs(self.x) + abs(self.y)
def __hash__(self):
return hash((("x" + str(self.x)), ("y" + str(self.y)), self.distance))
def __eq__(self, other):
return self.x, self.y, self.dista... |
c55b86b1ab2607740a1995eac41953caebb746f6 | Sibgathulla/LearnPython | /Encryption/EncryptionSHA256.py | 1,139 | 3.5 | 4 | import hashlib
def GetChar(idx):
return chr(idx)
def StringToHash256(input):
result = hashlib.sha256(input.encode())
return result.hexdigest()
def GenerateData(len):
print('GenerateData of length.. '+str(len))
indx=1
while(indx<=len):
for i in range(97,97+26):
j=1
... |
56a38332bec2e02606c3dceaa29ecade8bcdc7a0 | prakhar21/Learning-Data-Structures-from-Scratch | /stack/twostacks_onearray.py | 1,679 | 3.90625 | 4 | class Stack:
def __init__(self, size):
self.lst_stack = [None]*size
self.top1=-1
self.top2=size
def check_overflow(self, stack):
if stack==1:
if self.top1==self.top2-1:
return True
else: return False
else:
if self... |
dcbc049a883fe018e38b7a55b4ac461da73668e3 | prakhar21/Learning-Data-Structures-from-Scratch | /deque/deque_using_linkedlist.py | 2,071 | 3.890625 | 4 | class Node:
def __init__(self, data=None, prev=None, next=None):
self.val = data
self.next = next
self.prev = prev
class Deque(Node):
def __init__(self):
self.head = None
self.size = 0
self.rear = None
def insertFront(self, val):
tmp = Node(data=... |
4956212c52cce9d6b97d6ba588052161c03b239a | prakhar21/Learning-Data-Structures-from-Scratch | /tree/height_of_tree.py | 848 | 3.984375 | 4 | class Node:
def __init__(self, data=None):
self.data = data
self.left = None
self.right = None
def insert(self, val):
if self.data:
if val < self.data:
if self.left is not None:
self.left.insert(val)
else:
... |
1de568d0906cbb3b8de4541012425fc00839d391 | prakhar21/Learning-Data-Structures-from-Scratch | /tree/left_view_of_tree.py | 1,154 | 3.9375 | 4 | class Node:
def __init__(self, data=None):
self.data = data
self.left = None
self.right = None
def insert(self, val):
if self.data:
if val < self.data:
if self.left is not None:
self.left.insert(val)
else:
... |
720cb12baf17510689f3818b15e21ad9745bd7ad | prakhar21/Learning-Data-Structures-from-Scratch | /misc/distince_element_in_allwindow_sizek.py | 657 | 3.515625 | 4 | def count_distinct(sub_list):
tmp_cnt = {}
for element in sub_list:
if element in tmp_cnt:
tmp_cnt.pop(element)
else:
tmp_cnt[element] = True
return len(tmp_cnt.keys())
def create_window(data, k):
windows = []
for idx in range(len(data)):
tmp = data[i... |
2373663e0971d644f789b6c688616d3e5c2fff58 | sopoour/robotics | /LEGO Robot/sokoban.py | 2,029 | 3.953125 | 4 | from collections import deque
def main(graph, robotPos, canPos, canGoal):
path = planner(graph, canPos[0], canGoal[0])
robotGoTo = robotPathToCan(graph, path, robotPos[0])
robotPos[0] = path[len(path)-2]
print("Robot pos: ", robotPos)
finalPath = robotGoTo + path + robotPos
if path:
pr... |
8c66d4beff3d6bb8e4364559780ce307288960ca | maulxandr/maul-homework2 | /task_triangle_ya.py | 601 | 3.796875 | 4 | AX = int(input())
AY = int(input())
BX = int(input())
BY = int(input())
CX = int(input())
CY = int(input())
# Вычислим длины сторон треугольника
AB = ((AX - BX) ** 2 + (AY - BY) ** 2) ** 0.5
BC = ((BX - CX) ** 2 + (BY - CY) ** 2) ** 0.5
AC = ((AX - CX) ** 2 + (AY - CY) ** 2) ** 0.5
# Выполним проверку, является ли тр... |
96e2e0d4ccfdb550673860199813c5467b83fe9f | rmedalla/5-2-18 | /Calculator.py | 429 | 4.1875 | 4 | first_number = int(input("Enter first number: "))
math_operation = input("Choose an operand +, -, *, /: ")
second_number = int(input("Enter second number: "))
if math_operation == "+":
print(first_number + second_number)
if math_operation == "-":
print(first_number - second_number)
if math_operation == "*":
... |
e12b4feccf16912ed4f792fcb3b3d99c91897903 | ocastudios/glamour | /utils/__init__.py | 364 | 3.90625 | 4 | def reverse(original):
if original.__class__ in (int, float):
return original * -1
elif original.__class__ == str:
if original == "right":
return "left"
elif original == "left":
return "right"
elif original == "up":
return "down"
elif ... |
7ba408f380547e2078dcc3163031f028cdf188a7 | achmat-samsodien/RealPython | /factors.py | 188 | 4.09375 | 4 |
pos_int = int(raw_input("Enter a positive integer:"))
for divisor in range(1, pos_int+1):
if pos_int % divisor == 0:
print "{} is a divisor of {}".format(divisor, pos_int)
|
327b3354f5924358273de9be284627d37520fbba | Nozzin/Age-to-100 | /Age 100.py | 386 | 4 | 4 | def main():
age = int(input('What is your age? '))
name = input('What is your name? ')
year = 2016
while age < 100:
age +=1
year +=1
howMany = int(input('How many times do you want the message? '))
for i in range(howMany):
print ('Hello',n... |
5d7d2000c3d88ad79374e2e48c3b605cbaaee407 | Shivang1983/Application-Oriented-Programming-Using-Python | /Range.py | 108 | 3.5 | 4 | def func1():
for i in range(1000,2000):
if (i%7)==0 and (i%5)!=0 :
print(i)
func1() |
65887fd941b6b46332fed42aed93fa35f0f30eeb | Humaira-Shah/ECE499 | /asst2/AX12funcADJUSTED.py | 2,519 | 3.84375 | 4 | # FUNCTION getChecksum(buff)
# Takes packet as a list for its parameter.
# Packet must include at least 6 elements in order to have checksum calculated
# last element of packet must be the checksum set to zero, function will return
# packet with correct checksum value.
def getChecksum(buff):
n = len(buff)
if(n >= ... |
d16363c7abfa5cfa0435f4bb3a71e835d69b7fba | ryneches/Ophidian | /ACUBE/blob.py | 6,846 | 3.609375 | 4 | #!/usr/bin/env python
# vim: set ts=4 sw=4 et:
"""
Utility functions for building objects representing functions from
computed values.
"""
class SplineError(Exception) :
pass
class spline :
"""
This is a "natural" spline; the boundary conditions at the beginning
and end of the spline are such that the... |
7dda5fbfaf023f50773d680aad4947ad2a61dad2 | g-m-b/Data-structures-and-algorithms | /selection_sort.py | 329 | 3.65625 | 4 | def select_sort(a):
for i in range(len(a)):
min_pos=i
for j in range(i,len(a)):
if a[j]<a[min_pos]:
min_pos=j
a[i],a[min_pos]=a[min_pos],a[i]
if __name__ == '__main__':
a=[10,6,5,4,3,2]
select_sort(a)
for i in range(len(a)):
prin... |
f5cc1786452e20b10771998ffa44cf0f130ef4be | evanpeck/ethical_engine | /python/student_code/main.py | 815 | 3.65625 | 4 |
from engine import decide
from scenario import Scenario
def runSimulation():
''' Temporarily putting a main function here to cycle through scenarios'''
print("===========================================")
print("THE ETHICAL ENGINE")
print("===========================================")
print()
... |
3ceee61fb8757295c4d165ccb1ccdbb53ce6afc4 | jringenbach/labyrinth | /labyrinth/labyrinth.py | 14,718 | 3.5625 | 4 | #Python libraries
import os
import platform
import time
import xlrd
#Project libraries
from labyrinth.element import Element
from labyrinth.node import Node
class Labyrinth:
def __init__(self, file_name=None, labyrinth=list()):
"""
file_name (str) : name of the file where the labyrinth is sav... |
721e70fd5d2a3cb8c30895f8a9e8c8f6531c73d3 | aren945/pythonWay | /OOP/ObjectInfo.py | 905 | 3.671875 | 4 | # 使用type()
# 判断对象类型,使用type
type(12)
import OOP.ClassDemo as ClassDemo
a = ClassDemo.Man('zheng', 100)
print(type(123))
print(type(a))
import types
def fn():
pass
print(type(fn))
# 判断是否是函数
print(type(fn) == types.FunctionType)
print(type(x for x in range(10)) == types.GeneratorType)
# 判断继承关系
print (isinsta... |
b6ef34d8c45e06da767d0dedd818ba215780fa27 | aren945/pythonWay | /切片.py | 318 | 3.59375 | 4 | l = ['a', 'b', 'c', 'd']
a = list(range(100))
# print(type(a))
print(a[1:3])
print(a)
# from collections import Iterable
# print(isinstance('adc', Iterable))
for i, val in enumerate(l):
print(i)
c = [1, 2, 3, 4, 5, 6]
print('min is %d' % min(c))
ll = [(1, 2), (4, 5), (7, 8)]
for x, y in ll:
print(x, y) |
01bd112fa9f40534dd7dc96f293768d2a90bd578 | aren945/pythonWay | /learnDecorator.py | 1,899 | 3.5625 | 4 | import functools
def d1(func):
@functools.wraps(func)
def wrapper():
print('1234')
print(func())
return wrapper
@d1
def foo():
print('this is function fun')
return 'asd'
print(foo.__name__)
foo()
# --------------------------函数带参------------------------------
def d2(func):
... |
53cbd88eac06435fbf428d0141c666b489f18ffb | aren945/pythonWay | /advanced/map.py | 106 | 3.578125 | 4 | list_x = [1,2,3,4,5,6,7]
def square(x):
print(x)
return x * x
r = map(square, list_x)
print(list(r)) |
9d0a5ec66076a613f4b47e2bdb553a27e67cf028 | cherrycchu/AI-games | /sudoku.py | 4,895 | 3.78125 | 4 | #!/usr/bin/env python
#coding:utf-8
import queue as Q
import time
from statistics import mean, stdev
import sys
"""
Each sudoku board is represented as a dictionary with string keys and
int values.
e.g. my_board['A1'] = 8
"""
ROW = "ABCDEFGHI"
COL = "123456789"
def get_grids(row, col):
# get grids from row and ... |
b367f20e52abb94656d22cebda3cdf2fc533e2bb | havardMoe/euler | /problems/problem8.py | 501 | 3.890625 | 4 | """
The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.
Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?
"""
if __name__ == '__main__':
filename = "assets/p8_numbers.txt"
numbers... |
f8c1e91630c213360205d747e0dd573b3dbaed67 | Meemaw/Eulers-Project | /Problem_48.py | 400 | 3.796875 | 4 | __author__ = 'Meemaw'
print("Please insert upper bound:")
x = int(input())
print("Please insert last n numbers to be printed:")
last = int(input())
vsota = 0
for i in range(1,x+1):
vsota += i**i
if(last > vsota):
print("Sum doesnt have " +str(last) + " digits")
print("Sum: " + str(vsota))
else:
pr... |
a31ad7eb37c00469902946e4149192bba1b94363 | Meemaw/Eulers-Project | /Problem_37.py | 888 | 3.71875 | 4 | __author__ = 'Meemaw'
import math
def isPrime(stevilo):
if stevilo == 1:
return 0
meja = int(math.sqrt(stevilo)+1)
if(stevilo > 2 and stevilo % 2 == 0):
return 0
for i in range(3,meja,2):
if stevilo % i == 0:
return 0
return 1
def izLeve(stevilo):
for i in... |
90c9d41f6128b5d5d324f00a66bc9847abfa886b | ColtonPhillips/wpdb | /src/wpdb/wpdb.py | 701 | 3.6875 | 4 | def csv_file_to_list(csv_file_path):
"""Converts a csv file_path to a list of strings
>>> csv_file_to_list("test/csv_file_to_list_test.csv")
['Pascal', 'Is', 'Lacsap']
"""
import csv
out_list = []
with open(csv_file_path, 'rb') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',... |
863a17d68804499333542bc02eabbdb68080e66d | pratikbarjatya/Python-OOPS | /multilevel_inheritance.py | 512 | 3.609375 | 4 | class Father:
def father_property(self):
print('Father property used for home')
class Mother(Father):
def mother_property(self):
print('Mother property used for farming')
class Child(Mother):
def child_property(self):
print('child property used for playground')
... |
700af007f98f6ea5b0477b90804fc53499ac72c6 | jiangzhengfool/demo | /base.py | 10,125 | 3.84375 | 4 | # coding:utf-8
import re
# print ('江')
# flag = 'true'R
# if flag:
# print 'true'
# else:
# print 'false'
# n = 0
# count = 0
# while n <= 100:
# count += n
# n += 1
# print count
# print True
# def get_middle(s):
# #your code here
# str1 = s
# lens = len(s)
# if lens % 2 == 1:
# ... |
a4ce3d32406e1a613a6b076854f96d39027b35ee | umasp11/PythonLearning | /Datatype/InputData.py | 203 | 3.953125 | 4 |
'''ex= int(input('enter first number'))
#num1= int(input('enter first number')) #Typecasting
num2= float(input('enter second number'))
print(int(ex) +num2)'''
a=int (10.6)
b= float(5)
print(a+b) |
0badd45d54c90de31ce273519219cc0869f7da57 | umasp11/PythonLearning | /arg.py | 684 | 3.78125 | 4 | '''def sum(*ab):
s=0
for i in ab:
s=s+i
print('sum is', s)
sum(20,35,55,90,140)
'''
'''def myarg(a,b,c,d,e):
print(a,b,e)
list=[10,15,30,50,77] #no of parameter should be same as no of arguments
myarg(*list)'''
#Keyword argument **
def myarg(a,b,c):
print(a,b,c)
li={'a':10, 'b':... |
df9a22117bd98acc6880792e5c3c0273f270067d | umasp11/PythonLearning | /polymerphism.py | 1,482 | 4.3125 | 4 | #polymorphism is the condition of occurrence in different forms. it uses two method overRiding & overLoading
# Overriding means having two method with same name but doing different tasks, it means one method overrides the other
#Methd overriding is used when programmer want to modify the existing behavior of a method
... |
62c33ddc7ddc1daba876dd0422432686fcf361eb | umasp11/PythonLearning | /Threading.py | 890 | 4.125 | 4 | '''
Multitasking: Execute multiple task at the same time
Processed based multitasking: Executing multi task at same time where each task is a separate independent program(process)
Thread based multitasking: Executing multiple task at the same time where each task is a separate independent part of the same program(proce... |
fcdc70fdcb9d1125a2f01afc8d71123b29379733 | mc811mc/cracking-python-bootcamp | /the_python_virtual_atm_machine.py | 969 | 3.71875 | 4 | import time
from datetime import datetime
class ATM:
def __init__(self, name, pin):
pass
#else:
# raise ValueError("Invalid Account User")
def deposit(self):
print("{'transaction': ['" + datetime.now() "', " + amount +"]}")
return self.deposit
def withdrawal(s... |
1dd9db0d99ccb4bb22d75d0dfcdc42f59c9b70ca | M-Sabrina/AdventOfCode2020 | /Tag-15/rambunctious_recitation2.py | 1,245 | 3.5625 | 4 | import numpy as np
def rambunctious_recitation2(contents):
start_numbers = contents.split(",")
numbers_array = np.array([int(number) for number in start_numbers])
turn_dict = {}
for ind, number in enumerate(numbers_array[:-2]):
turn_dict[number] = ind
turn = len(numbers_array) - 1
la... |
f35e1fd8ae959c88cde48bf9f24ca460704407b3 | dapao1/python | /汉诺塔.py | 412 | 4 | 4 | def hanoi(n,x,y,z):#数量,原位置,缓冲区,目标位置
if n==1:
print(x,'--->',z)#将1从x移动到终点z
else:
hanoi(n-1, x, z, y)#将前n-1个盘子从x移动到y上
print(x,'-->',z)#将最底下的最后一个盘子从x移动到z上
hanoi(n-1,y,x,z)#将y上的n-1歌盘子移动到z上
n=int(input('请输入汉诺塔的层数:'))
hanoi(n,'X','Y','Z')
|
3c582e745d16072b8be72e653c2303770b4983d2 | arthurlambert27/Hangman | /pendu.py | 1,078 | 3.578125 | 4 | import random
def affichage_mot(mot, lettreTrouve):
final = ""
for i in mot:
final = final + "*"
for a in lettreTrouve:
if a == i:
final = final[:-1]
final = final + i
return(final)
rejouer = 1
li... |
a91cf716b618752bc6d8e39c3edd1df0935d109d | developerhat/project-folder | /hangman_4.py | 364 | 3.84375 | 4 | #Hangman game
import random
word = random.choice(['Subaru','Tesla','Honda','BMW'])
guessed_letters = []
attempt_number = 7
print(word)
while attempt_number <= 7:
user_input = str(input('Input a letter: '))
if user_input in word:
print("You got it!")
else:
attempt_number -= 1
pri... |
1c5db35bcaff5b9c024aec2976dd3e6c94e482a9 | developerhat/project-folder | /SimplePrograms2.py | 6,168 | 3.8125 | 4 | #Simple Programs 2 to run scripts on
def numbers_sum(lst):
nums_only = []
for i in lst:
if isinstance(i, bool):
continue
elif isinstance(i, int):
nums_only.append(i)
else:
continue
return sum(nums_only)
def unique_sort(lst):
no_dupes = []
... |
8ec9acc3d100be489533d4a63ee4a42411c1ad94 | developerhat/project-folder | /SimplePrograms.py | 47,564 | 4.0625 | 4 | #Misc simple programs
#Counting vowels program (Incomplete)
def count_vowels(word):
vowels = 'aeiou'
count = 0
word = word.lower()
for vowel in vowels:
count = word.count(vowel)
print(count)
#Oh shoot it worked! Did this on my own. Had to look up reorganizing & adding FizzBuzz as firs... |
a6f7f06f6281317ea7ef81aeef1fc60e44fe51a7 | developerhat/project-folder | /Doing.py | 443 | 4.03125 | 4 | #This function is for addition
def add(x, y):
return x + y
#Function for subtraction
def subtract(x, y):
return x - y
#Function for multiplication
def multiply(x, y):
return x * y
#Function for division
def division(x, y):
return x / y
print("Welcome to Patrick's calculator! ")
print('\n' * 4)
print("Ent... |
288dc860f25c3ddea6610726bb6547893f1e3a1c | developerhat/project-folder | /October.py | 14,755 | 3.96875 | 4 | #usr/bin/python
#This loop will print hello 5 times
spam = 0
#Will print hello until spam is equal to or greater than 5
while spam < 5:
print('Hello ')
spam = spam + 1
#Code below keeps asking for input until you type your name
#Programmer humor?
name = ' '
while name != 'your name':
name = str(input('P... |
1f299c522d6430d5a7c4301e56a789d8e2192597 | developerhat/project-folder | /CreateFolder.py | 266 | 3.625 | 4 | #Creating folder using python
import os
path = "/Users/patrickgo/Desktop/Misc/NetDevEng"
os.mkdir(path)
print(os.getcwd())
print("\n")
print("All of the files & folders in this directory are: \n",os.listdir())
#Prints current working directory + sublists & files
|
24cda752498f51e747e869109f81da988089ca5a | developerhat/project-folder | /oop_practice.py | 608 | 4.125 | 4 | #OOP Practice 04/08/20
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@patgo.com'
def fullname(self):
return '{} {}'.format(self.first, self.last)
emp_1 = Employee('pat','... |
8b6dc2a503a73d243151605477c060e0db85fb70 | PeterLemon/N64 | /Compress/DCT/DCTBlockGFX/DCTEncode.py | 3,755 | 3.703125 | 4 | import math
# DCT Encoding: "https://vsr.informatik.tu-chemnitz.de/~jan/MPEG/HTML/mpeg_tech.html"
# DCT Value At The Upper Left Corner Is Called The "DC" Value.
# This Is The Abbreviation For "Direct Current" & Refers To A Similar Phenomenon
# In The Theory Of Alternating Current Where An Alternating Current Can Have... |
3dd6343d9218eec78dd061d58d6adf0292f74517 | aturfah/cmplxsys530-final | /ladder/random_ladder.py | 1,115 | 3.875 | 4 | """Ladder that randomly pairs two agents."""
from random import random
from ladder.base_ladder import BaseLadder
class RandomLadder(BaseLadder):
"""Ladder that matches players randomly."""
def __init__(self, game=None, K_in=32, selection_size=1):
"""
Initialize a ladder for a specific game.
... |
a68961fdb55a4ce92f150f10d4173ab89eec6aec | musthafashaik126/PythonFundamentals | /Day 7_B 28_python.py | 478 | 4.03125 | 4 | age = 22
if age >= 15:
print("you are eligible to vote")
else:
print("you are not eligible to vote next year")
year = 20
if year >= 55:
print("you are eligible to i cet exam ")
else:
print("you are not eligible to i cet exam")
age = 1
if age == 1:
print("baby will be able to crowl")
e... |
148b8cdd616b477d3824de4646ae3d4109256acf | dgoat416/Terminal_Blog | /Testing MongoDB.py | 2,028 | 3.734375 | 4 | __author__ = "DGOAT"
import pymongo
# exactly where on the mongoDB server we are connecting to
uri = "mongodb://127.0.0.1:27017"
# initialize the mongoDB client which has access to all databases in
# mongoDB instance
client = pymongo.MongoClient(uri)
database = client['fullstack']
collection = database['students']
... |
88d72128cbb1a2073dcad72f2befc06105dd9ef2 | Nibinsha/python_practice_book_updated | /chp5/prbm1.py | 376 | 3.84375 | 4 | class reverse_iter:
def __init__(self,n):
self.i = 0
self.n = n
def next(self):
if self.i < self.n:
x = self.n
self.n -= 1
return x
else:
raise StopIteration()
a = reverse_iter(5)
print a.next()
print a.next()
print... |
2a7b37dbb0a6fac11b0e9ca2541c0f2e1cb7a1e1 | Nibinsha/python_practice_book_updated | /chp2/prbm14.py | 176 | 3.671875 | 4 | def unique(x):
l = []
for i in x:
s = i.lower()
if s not in l:
l.append(s)
return l
print unique(['Abc','A','ab','abc','a'])
|
18821aa2c606ee4838ea45fd91049589a352330b | Nibinsha/python_practice_book_updated | /chp2/prbm31.py | 134 | 3.546875 | 4 | def parse(x,y,z):
f = open(x).readlines()
print [[i.split(y)] for i in f if f[0] != z]
print parse('parse_csv.txt','!','#')
|
29eb770fffa63d9e89a1cac09de9184e1076abc2 | Nibinsha/python_practice_book_updated | /chp2/prbm2.py | 88 | 3.5 | 4 | def sum(x):
c = 0
for i in x:
c+=i
return c
print sum([1,2,3,4,5])
|
aae732bd6ddb3e12e17a472ca210a9df08803456 | Nibinsha/python_practice_book_updated | /chp2/prbm4.py | 101 | 3.671875 | 4 | def product(x):
mul = 1
for i in x:
mul*=i
return mul
print product([1,2,3,4])
|
140ebcf7e2d06b1743f6720946cc267728494dbd | johnny3young/codingame | /puzzles/python2/ascii_art.py | 382 | 3.796875 | 4 | width = int(raw_input())
height = int(raw_input())
text = raw_input().upper()
for i in range(height):
row = raw_input()
output = ""
for char in text:
position = ord(char) - ord("A")
if position < 0 or position > 25:
position = 26
start = position * width
end = sta... |
81a7eedaa50f6053f34f436d2fba9d2481b8d568 | sungsoo-lim90/RL_HWs | /HW1/policy_iteration_multiclass.py | 6,736 | 4.0625 | 4 | """
MSIA 490 HW1
Policy iteration algorithm - multiclass
Sungsoo Lim - 10/19/20
Problem
- One state is assumed that represents the number of customers at the station at given time
- Two actions are assumed that either a bus is dispatched or it is not at given time and state
- Reward is assumed to be negative, as there... |
77e69bb4ca02c4add43f751ffc699d93f689d8bb | Mask-of-the-Fractal-Abyss/cryptodungeon4 | /playerCommands.py | 1,266 | 3.65625 | 4 | from tools import *
# Player searches for desired code
def search(codeToSearch):
if player.room is None:
if codeToSearch in codeClass.codes:
room = searchRoomsByCode(codeToSearch)
middle = int(room.size / 2)
room.contents[middle][middle] = player
p... |
69ea978428cde6f9a9023dc720b677564b1d1cec | wilhelmwen/password_retry | /pwretry.py | 263 | 3.90625 | 4 | x = 3
while x > 0:
x = x - 1
pw = input ('請輸入密碼: ')
if pw == 'a123456':
print('登入成功')
break
else:
print('密碼錯誤!')
if x > 0:
print('還有', x, '次機會')
else:
print('沒機會嘗試了! 要鎖帳號了啦!')
|
48b9d1c567012e7e766286f198f0c45903553bb4 | HTeker/Programmeeropdrachten | /12.py | 1,509 | 3.765625 | 4 | def printMatrix(cells):
for i in range(0, len(cells)):
row = ""
for x in range(0, len(cells[i])):
row += "["
if(cells[i][x] == 0):
row += " "
elif(cells[i][x] == 1):
row += "X"
else:
row += "O"
... |
a72050671b14bd9b9a245434503da04d1024ca3a | SamarthaSinghal/P---105 | /105.py | 497 | 3.75 | 4 | import math
import csv
with open ('data.csv',newline = '') as f :
reader = csv.reader(f)
data = list(reader)
data1 = data[0]
def mean (data1):
n = len (data1)
total = 0
for x in data1 :
total = total+int(x)
mean = total/n
return mean
list = []
for i in data1 :
a = int(i) - mean... |
3b35bc7cc7235aba585d37bf014450b52767bafd | uppaltushar/hello-git | /assignment-2.py | 410 | 3.953125 | 4 | #1>
print("tushar Uppal")
#2>
str1 = "uppal"
str2 = "tushar"
print(str1+str2)
#3>
p = int(input("enter "))
q = int(input("enter "))
r = int(input("enter "))
print("p = ",p,"q = ",q,"r = ",r)
#4>
print("let's get started")
#5>
s = "Acadview"
course = "python"
fees = 5000
str1 = "{} {} course fee is {}".format(s,... |
d89b6e9450cb2bac5a603394f6da53e8381c500f | pavansaij/Algorithms_In_Python | /ThreadSafe_Dict/mutable_dict.py | 737 | 3.640625 | 4 | class MutableDict():
def __init__(self, *args, **kwargs):
self.__dict__.update(*args, **kwargs)
print(self.__dict__)
def __setitem__(self, key, value):
self.__dict__[key] = value
def __getitem__(self, key):
return self.__dict__[key]
def __delitem__(self, key):
de... |
5a0ca6f1c602ce3a41a722d1d208daa131de6bb1 | renanpaduac/linguagem_programacao | /exercicio4.py | 244 | 3.671875 | 4 | for nr in range(2,100):
print(nr, end=' - >')
primo = True
x = 2
while x < nr and primo:
if nr %x == 0:
primo = False
x+=1
if primo:
print("VERDADEIRO")
else:
print ("FALSO")
|
2fc98fec393d40e8163c47aba7c5fd64ae076501 | mbeissinger/recurrent_gsn | /src/models/lstm.py | 809 | 3.546875 | 4 | """
LSTM with inputs, hiddens, outputs
"""
import torch
import torch.nn as nn
class LSTM(nn.Module):
def __init__(self, input_size, hidden_size, output_size,
num_layers=2, bias=True, batch_first=False,
dropout=0, bidirectional=False, output_activation=nn.Sigmoid()):
super().__init__()
... |
f80ce721837ae4b782981bba552681f886663ddb | girish75/PythonByGireeshP | /pycode/Question8listfunction.py | 2,252 | 4 | 4 | # Q8. Given a list, l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9], store 3 sub-lists such that those
# contains multiples of 2, 3 and 4 respectively. Print the lists.
# Repeat storing and printing the lists same as above as multiples of 2, 3 and 4 but take
# l1 as [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].
l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
l2... |
116936cad73564abb9355199f5c8604d0b0bb8e7 | girish75/PythonByGireeshP | /pycode/Quesetion1assignment.py | 925 | 4.40625 | 4 | # 1. Accept user input of two complex numbers (total 4 inputs, 2 for real and 2 for imaginary part).
# Perform complex number operations (c1 + c2, c1 - c2, c1 * c2)
a = int(input("For first complex number, enter real number"))
b = int(input("For first complex number, enter imaginary number"))
a1 = int(input("For sec... |
ac235a932c259aac16a2a47fe0a45f9255e8a6f0 | girish75/PythonByGireeshP | /pythonproject/FirstProject/jsong.py | 1,813 | 4.3125 | 4 | import json
'''
The Json module provides an easy way to encode and decode data in JSON
Convert from Python to JSON:
If you have a Python object, you can convert it into a JSON string by using the json.dumps() method.
convert Python objects of the following types, into JSON strings: dict, list
tuple, string... |
f34b378c7bf7ee5a4f0c7263274312064a3ab596 | girish75/PythonByGireeshP | /pycode/newfunction.py | 696 | 4.09375 | 4 | def hello():
print("This is hello function")
# function to find factorial
def fact(n):
""" function to find factorial value"""
# print("Factorial function called" )
if n == 1:
return 1
else:
return (n * fact(n-1))
# Define `main()` function
def main():
hello()
print("This... |
8fec3c271497a7556c4c28ae307c8e686a2b1eb3 | girish75/PythonByGireeshP | /pycode/original1.ListComprehensions.py | 593 | 4.03125 | 4 | nums = [0, 1, 2, 3, 4]
print("Creating Empty list...")
print(nums)
squares = []
for x in nums:
print("Creating square list and appending square of = " + str(x))
squares.append(x ** 2)
print("Printing new list with squares .. ")
print(squares) # Prints [0, 1, 4, 9, 16]
print("list comprehensions..")
nums = ... |
30d6c602a49a9470a33a49b0d14762025e4743b3 | suberlak/quasars-sdss | /SF_plotting/FileIO.py | 4,905 | 4.03125 | 4 | import numpy
import os.path
def ReadColumns(FileName, ncols=None, delimiter='', comment_character='#', verbose=True):
""" Read a number of columns from a file into numpy arrays.
This routine tries to create arrays of floats--in this case 'nan' values
are preserved. Columns that can't be cast as floats are... |
6de8d2f46212c6c92213b5901a5e82ab2d692112 | manasviKnarula/LaterThan30Days | /RemoveFiles.py | 330 | 3.5625 | 4 | import time
import os
import shutil
path = input ("please enter the path for your folder: ")
days = 30
time.time(days)
if os.path.exists(path+"/"+ext):
os.walk(path)
os.path.join()
else:
print("path not found")
ctime=os.stat(path).st_ctime
return ctime
if ctime>days:
os.remove(path)
shutil.rmtre... |
1bac046ce2443b8e1cd93566bf59b0e8800755be | PlasticTable/Python-Stuff | /Function Scoping Example.py | 204 | 3.6875 | 4 | lis1 = [1,2,3,4]
def random(lis1):
lis2 = []
for i in lis1:
lis2.append(i)
return lis2
print random(lis1)
print random([9,4,3,2])
# Very ugly and confusing code
# Was wondering why it worked
|
cee82ae95620940abc124cafe4ec4ffb6fab9da2 | aarthisandhiya/aarthisandhiya1 | /11hunter.py | 187 | 4.09375 | 4 | def reverse(sentence):
words=sentence.split(" ")
newWords=[i[::-1] for i in words]
newSentence=" ".join(newWords)
print(newSentence)
sentence=input()
reverse(sentence)
|
f710d6d6500b31254ea5c628a15733402bcfcd36 | himal8848/Data-Structures-and-Algorithms-in-Python | /linear_search.py | 307 | 4.09375 | 4 | #Linear Search In Python
#Time complexity is O(n)
def linear_search(list,target):
for i in range(len(list)):
if list[i] == target:
print("Found at Index ",i)
break
else:
print("Not Found")
list = [4,6,8,1,3,5]
target = 5
linear_search(list,target) |
2196af2ef6617fbba8292dda5aed2649e1aac0a3 | himal8848/Data-Structures-and-Algorithms-in-Python | /bubble_sort.py | 315 | 4.1875 | 4 | #Bubble Sort in Python
def bubble_sort(list):
for i in range(len(list)-1,0,-1):
for j in range(i):
if list[j] > list[j+1]:
temp = list[j]
list[j] = list[j+1]
list[j+1] = temp
list = [23,12,8,9,25,13,6]
result = bubble_sort(list)
print(list) |
79ffca882d5bb5261533611b4d03e9dc2175d7ab | jonovik/cgptoolbox | /cgp/sigmoidmodels/doseresponse.py | 5,817 | 3.65625 | 4 | """Functions for modelling dose-response relationships in sigmoid models"""
from __future__ import division
import scipy
import numpy as np
def Hill(x, theta, p):
"""
The Hill function (Hill, 1910) gives a sigmoid increasing dose-response
function crossing 0.5 at the threshold theta with a steepness determ... |
0c8d1f3f209e6509e22286834b9d45c063be5fd1 | jonovik/cgptoolbox | /cgp/examples/sigmoid.py | 4,618 | 3.734375 | 4 | """
Basic example of cGP study using sigmoid model of gene regulatory networks.
This example is taken from Gjuvsland et al. (2011), the gene regulatory model
is eq.(15) in that paper, and the example code reproduces figure 4a.
.. plot::
:width: 400
:include-source:
from cgp.examples.sigmoid import cgpst... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.