blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
fbdda50d4f1907b47f6aa7730b316e8a08db2ac3 | DenysGurin/DB2 | /DB2_limited.py | 2,320 | 4.0625 | 4 | import re
def handle_numbers(number1, number2, number3):
if type(number1) != int and type(number2) != int:
raise "Invalid input, function need number1(int), number2(int), number3 as parameters"
try:
why = ""
count = 0
for number in range(number1... |
3cbf569581b5e4b004a9938218b045ac95482c83 | jerryfane/Freebitco.in-Multiplier-Simulator | /script.py | 2,476 | 3.578125 | 4 | from random import randint
import logging
logging.basicConfig(filename='log.log',level=logging.DEBUG)
base_bet = 1 #Modificare qui
base_odd = 2 #Modificare qui
odd_lose = 2 #Modificare qui
lose_multiplier = 2 #Modificare qui
win_multiplier = 1 ... |
3386f67e071ef2a959641829a4de30e9a97363b8 | catharob/Python-INFO1-CE9990 | /graphpaper.py | 866 | 3.71875 | 4 | """
graphpaper.py
Tell me how big you want the squares to be in your graph paper, and how much you'd like of it, and I'll print it out for you.
"""
import sys
rows = int(input("How many rows of boxes? "))
columns = int(input("How many columns of boxes? "))
rSpace = int(input("How many rows of spaces in each box (e.... |
a0d3d5315ecd4fee418f52e719fd12e0ef25a0f4 | subham3947/SocialNetworkAnalysis | /filmtrust/NetProp.py | 1,023 | 3.546875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 11 16:13:36 2017
@author: nakul
"""
import networkx as nx
#Degree distribution
#Clustering Coefficient
def clusterCoeff(G):
print('Clustering Coefficient of the graph=',nx.average_clustering(G))
return
#Average Distance between two nodes and... |
5aa3b3d8e098e973de2bc201389a2d5288b243b1 | acconnitt/cse210-tc05 | /jumper/game/director.py | 2,319 | 3.78125 | 4 | from game.jumper import Jumper
from game.word import Word
from game.output import Output
class Director:
# Method initializer for the Director class
def __init__(self):
"""Attributesof of the class"""
"""Objects of the class"""
self.strikes = 0 # Strikes start at 0
self.jumpe... |
5ac2b332b355cd7d983a66a07e6616aa3db583db | saites/pool | /pool/sensors.py | 853 | 3.765625 | 4 | '''
Communicates with the sensors to obtain readings
'''
import random
pH = 7.0
def get_pH():
'''Returns current pH value.
note that value is adjusted by sensor probe based on temperature.
To update this value, use set_pH_temp_compensation.
'''
global pH
pH += .1
return pH + (random.rand... |
f0a4202a7af6e569fe28fed515d00f386f737dd9 | CurtisTrepte/Software | /main.py | 463 | 4.0625 | 4 | def main():
mainFunction = input("Hi and welcome to the software! What can I do for you?\n")
if mainFunction.upper() == "EXIT":
exit()
elif mainFunction.upper() == "CHICKEN":
print("Wassup")
#Get name and max
name = input("What is your name? \n")
age = int(input(f"Hello {name}, what is your age? \n"... |
3606689dd2eb6e56262ed157f252af622bcbd49a | th3n0y0u/C2-Leap-Year | /main.py | 426 | 4.40625 | 4 | # Prompt the user to input a year
year = int(input("Please input a year: "))
# Using if statements, output whether the inputted year is or is not a leap year
if(year < 0):
if(year // 100 != 0):
if(year % 400 == 0):
print("Your year is a leap year")
else:
print("Your year is not a leap year")
el... |
bfb57a3c2b9d3d575751b48e7c2708cecac5c552 | spudmind/undertheinfluence | /utils/fuzzy_dates.py | 3,542 | 3.9375 | 4 | # -*- coding: utf-8 -*-
import calendar
from datetime import datetime
import re
class FuzzyDate:
def __init__(self, date=None, index=None, text=None, date_format=None):
self.date = date
self.index = index
self.text = text
self.date_format = date_format
def __str__(self):
... |
da4e584522b12627573b2fba3b34070611f71337 | tigranv/Python-Starter | /PythonStarterFirstSteps/PythonOOP/Functions/Functions.py | 229 | 3.96875 | 4 |
def print_numbers(limit):
for i in range(limit):
print(i)
n = int(input("Enter limit: "))
print_numbers(n)
my_list = [1,2]
def add_to_list(some_list):
some_list.append(8)
add_to_list(my_list)
print(my_list) |
13802ce9eb6b974d5d8959eb5432a0e4ad6e8420 | ParkJinYeong211/NuCamp_Solitaire | /card.py | 1,122 | 3.515625 | 4 | class Card():
_suit: str
_value: int
_card_value: str
_isRed: bool
_flipped: bool
def _Get_Card_Value(self, value):
return dict(zip(range(1, 14), "A234567890JQK"))[value]
def __init__(self, suit, value):
if suit not in ["C", "D", "H", "S"]:
raise ValueError(f"{s... |
331318cc878822320c0dc161150451ecbf7b7283 | TomasTaniguchi/server-side-1 | /utils_test/stringtonumber.py | 151 | 3.609375 | 4 |
input = "@Cyberlink"
input = input.lower()
output = ""
for character in input:
number = ord(character) - 96
output += str(number)
print (output) |
d44189fc8b02007953699e88d8ebbb7d28199609 | programmingontape/demo | /fizz_buzz.py | 203 | 3.875 | 4 | x = range (1,100)
for y in x:
if y % 3 == 0 and y % 5 == 0:
print("FizzBuzz")
elif y % 5 == 0:
print("Fizz")
elif y % 3 == 0:
print("Buzz")
else:
print(y)
|
1fc368ff9113ec057fb8483d7ac8a3e965afed89 | aetooc/PF-Lab-Tasks | /L1Q2.py | 296 | 4.15625 | 4 | def function2(number):
factorial = 1
if number ==0:
print('1')
if number < 0:
print("Sorry, Please enter a Positive Integer")
else:
for i in range(1,number + 1):
factorial = factorial*i
print("The factorial of",number,"is",factorial)
|
5bca0f57725e5931a0e5c7e9ff46aa76e2082451 | purescript-python/pspy-tutorials-linear-algebra | /purescript_pytutorials/ffi/Data/Semigroup.py | 184 | 3.609375 | 4 | def concatString(s1):
return lambda s2: s1 + s2
def concatArray(xs):
return lambda ys: (
ys if not xs else
xs if not ys else
xs + ys
) |
5866fd7e3d318a79662c73d126548159f9d58a70 | plinek401/University-of-RI | /Intro to Machine Learning(ML)/Assignment1/class test.py | 7,073 | 3.609375 | 4 | import sys
import math
import pandas as pd
class Node():
def __init__(self, attribute, threshold):
self.attr = attribute
self.thres = threshold
self.left = None
self.right = None
self.leaf = False
self.predict = None
# First select the threshold of the attribute to split set of test data on
... |
bbdc237583606b8971ea7d116cbf3853a0b466ef | JefersonFG/upgma | /upgma.py | 4,233 | 3.84375 | 4 | # Global variables
subtree_list = {}
# Class definitions
class Subtree:
def __init__(self, a, b, distance):
self.a = a
self.b = b
distance_a = 0
distance_b = 0
if a in subtree_list:
self.a = subtree_list[a]
distance_a = subtree_list[a].middle
... |
54ad29f03f118388d70c3fcee34b7e5d72c033c3 | noahdagne/Public-Past-Projects | /Small Python Assignment/Dagne-hw6-1.py | 227 | 3.890625 | 4 | # Noah Dagne
# INST326
x = [1, 2, 3, 4, 5]
y = [4, 5, 6, 7]
def list_intersection(x, y):
for vals in x:
for vals2 in y:
if vals == vals2:
print(vals)
return vals
list_intersection(x, y)
|
aae3f27b5b1387e5a7b956fbba4081b4ad649a34 | Precute/preciouspython_repo | /ex_11.py | 570 | 4.09375 | 4 | counts = dict()
print("enter file name")
filename = input('')
if len(filename) < 1:
filename = 'clown.txt'
filename = open(filename)
for line in filename:
line = line.rstrip()
words = line.split()
for word in words:
# print(word)
counts[word] = counts.get(word, 0) + 1
maxcount = None
com... |
31438aa569157d79a1112a5fee28eb7446dcdc1a | Precute/preciouspython_repo | /ex_07.py | 499 | 4 | 4 | def calculate_average(total, times):
return total/times
total_input = 0.0
number_of_times = 0
while True:
user_input = input("Enter a number: ")
if user_input == 'done':
break
try:
float_user_input = float(user_input)
total_input = total_input + float_user_input
number_of... |
2060779b998e7902cfd00cc02616613b290429f8 | firstvan/Python | /hf/5hf/6kiralyno.py | 542 | 3.5625 | 4 | #!/bin/python2
# encoding: utf-8
def kiralynok(li):
"""Draw the 8 queen chessboard
Queens position in the list. Positions starts with 0 and the from bottom"""
print "+-----------------+"
for j in range(len(li)):
print "|",
for i in li:
if i == 7-j:
print... |
a57cd91e70e7cea4fc53f9c1f6e7f9d872a6f4dc | firstvan/Python | /hf/4hf/listcomp.py | 1,350 | 3.578125 | 4 | #!/bin/python2
def main():
li = ['auto', 'villamos','metro']
li = [szo.upper()+'!' for szo in li]
print li
li = ['aladar', 'bela', 'cecil']
li = [szo.capitalize() for szo in li]
print li
li = [0 for n in xrange(10)]
print li
li = [n for n in xrange(1,10+1)]
li = [2*n ... |
4bbf06f6c08dbbbd3456bd7c0e8a8c2f7a0b05e7 | bewheat/SE126 | /List_demo/List_demo/List_demo.py | 1,543 | 4.3125 | 4 | #Desiree Daviw
#List Demo
#SE 126.22
#1/29/20
#PROMPT: Write a program that reads the data file (below) and stores the data into lists. then, process the lists to reprint the file data, record by record. Next, reprocess the lists to find each student's current average score along with the class average. Store each ... |
28ec4a8af651f58cbebdb526866e4192a558fb14 | bewheat/SE126 | /Practice Prompt 1/Practice Prompt 1/Practice_Prompt_1.py | 2,268 | 4.40625 | 4 | #Desiree Davis
#Practice 1
#SE126.22
#1/1/20
#Prompt: Write a Fahrenheit-to-Celsius conversion program that allows the user to enter as many temperatures in Fahrenheit they would like.
#Variable Library:
# sumtotalTemps: will hold sum of all Fahrenheit tems
# totalTemps: will hold total number of all Fahrenheit ... |
e5207f0ecfe8b26aa04b653a8d4fb8d0549a2501 | NikitaYasinski/client-server | /test.py | 299 | 3.84375 | 4 | alpha = 'абвгдеежзийклмнопрстуфхцчшщъюьэюя'
n = int(input("Ключ:"))
s = input("Введите текст для зашифрования:").rstrip()
res = ''
for c in s:
res += alpha[(alpha.index(c) + n) % len(alpha)]
print('Результат: ' + res) |
da4a97ae6d14ff17b6b1af3ab82a83743f8c1e1e | byklo/mit-python | /algorithms/set_diff.py | 503 | 3.78125 | 4 | # set difference
# given A = [ 1 2 3 4 ], B = [ 3 4 5 6 ], return D = [ 1 2 5 6 ]
import random
def set_diff(a, b):
duplicates = {}
uniques = {}
combined = a + b
for x in combined:
if x in uniques:
duplicates[x] = 1
else:
uniques[x] = 1
output = []
for x in combined:
if x not in duplicates:
outpu... |
255c1044c9718ef23a913518973a823312a06664 | byklo/mit-python | /algorithms/sorting/bubbleSort.py | 529 | 4.15625 | 4 | #!/usr/bin/python
import sys
def bubbleSort(a, verbose):
unsortedLength = len(a)
while unsortedLength > 0:
for i in xrange(unsortedLength):
if i != unsortedLength - 1 and a[i] > a[i+1]:
print "// swapping %s with %s" % (a[i], a[i+1])
temp = a[i]
a[i] = a[i+1]
a[i+1] = temp
if verbose:
... |
572667a503432f53d9689fc40676464086e8ed8b | byklo/mit-python | /cracking/recursion_and_dp/stringpermutations.py | 723 | 3.578125 | 4 | # Write a method to compute all permutations of a string
import random
import math
def printperm(prefix, s):
if len(s) == 0:
print prefix
else:
for c in s:
modified = list(s)
modified.remove(c)
printperm(prefix + c, modified)
# TIME = O(n!)
def countperm(s):
if len(s) == 0:
return 1
else:
count... |
2016ab970f7ffded09999a1b23865db442f10fda | byklo/mit-python | /datastructures/minmaxheap.py | 4,875 | 3.75 | 4 | import random
import heapq
# will implement min-max heaps using a min and a max heap
# the heaps are normal heaps but the important part is that they need
# to have a remove(item) method. the implemented remove(item) method
# runs in O(lg n) time so O(lg n) time overall is preserved for
# all heap operations.
def swa... |
21182567db07ce74857332dbd25954239ff20bce | byklo/mit-python | /algorithms/spree/rm_dupes_in_sorted_ll.py | 962 | 3.84375 | 4 | # Given a sorted linked list, delete all duplicates such that each element appear only once.
#
# For example,
# Given 1->1->2, return 1->2.
# Given 1->1->2->3->3, return 1->2->3.
import random
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def ... |
6da7841b9fdb4819b92f6b2ec25f7ba12d388488 | byklo/mit-python | /cracking/recursion_and_dp/magicindex.py | 962 | 3.828125 | 4 | # A magic index in an array A[1 .. n-1] is defined to be an index such that A[i] = i.
# Given a sorted array of distinct integers, write a method to find a magic index, if one exists, in array A.
import random
def magic_linear(a):
# O(n) iterate through the elements checking A[i] = i
for (i, x) in enumerate(a):
i... |
ff3ed5070844041749c77a4fa20430bf2c696f80 | byklo/mit-python | /algorithms/threesum.py | 452 | 3.6875 | 4 | import random
# O(n^2) solution with O(n) space complexity
def threesum(a, x):
for i,y in enumerate(a):
target = x - y
log = {}
for j,w in enumerate(a):
if y == w:
continue
z = target - w
if log.has_key(z):
return (i, log[z], j)
else:
log[w] = j
return None
a = random.sample(xrange(20)... |
2104aa368aa5a09139a3f156385f4f043ba46de2 | byklo/mit-python | /cracking/recursion_and_dp/parens.py | 947 | 3.515625 | 4 | # Implement an algorithm to print all valid (i.e., properly opened and closed) combinations of n-pairs of parentheses.
import random
def parens(pre, n, close):
if n == 0 and close == 0:
print pre
else:
if n == 0:
parens(pre + ")", n, close - 1)
elif n == close:
parens(pre + "(", n - 1, close)
elif n <... |
76a02cca7dac7215a2f03322f82e61d5da020f90 | byklo/mit-python | /algorithms/reverse_linked_list.py | 576 | 3.921875 | 4 | # reverse a linked list
import sys
class Node(object):
def __init__(self, val):
self.val = val
self.next = None
def print_ll(head):
cur = head
while (cur is not None):
sys.stdout.write("%s -> " % cur.val)
cur = cur.next
print ""
def reverse_ll(head):
values = []
cur = head
while (cur is not None):
... |
442e45be622fcdb742bf5d726a3f0c6576703b72 | byklo/mit-python | /python-ref/conditions.py | 1,672 | 4.25 | 4 | # pretty standard
# and == && , or == ||
myfavrapper = "kendrick"
herfavrapper = "chance"
myfavbeer = "sweetgrass"
herfavbeer = "flying"
myfavband = "the1975"
herfavband = "the1975"
if myfavrapper == herfavrapper:
print "Our fav rapper is %s" % myfavrapper
else:
print "We don't share a fav rapper"
if myfavbeer ==... |
ac6ba09954b9199b31eb6e8c0b03d1996b467126 | Gauravrana1/spychat | /main.py | 1,731 | 3.765625 | 4 | import chat
while 1==1:
print"###WELCOME BACK TO SPYCHAT###"
print"SELECT OPTION"
print"\t1.LOG IN:\n\t2.SIGN UP:"
choose = raw_input("")
if choose == "2" or choose == "2":
i = False
while i != True:
spy_name = {
'Name': '',
'Sal... |
d5752983bd5682056cea0ecb26134ef55c86518e | manthan787/algo-practice | /stack/reverse_polish_notation.py | 1,031 | 3.8125 | 4 | '''
https://leetcode.com/problems/evaluate-reverse-polish-notation/description/
Evaluate Reverse Polish Notation.
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
'''
class Solution(object):
def evalRPN(self, tokens):
"""
:type tokens: List[str]
... |
8aeaccc1771e1e8da12f6ab3610226fbe22c68bb | manthan787/algo-practice | /trees/expression_eval.py | 1,183 | 3.890625 | 4 | from __future__ import print_function, division
# Tree Node definition
class Tree(object):
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def evaluate(n):
''' Evaluate a tree containing arithmetic expression rooted
at `n`.
'''
if not n: ... |
02d3f09892d5191bccba36530717244a28e9035e | manthan787/algo-practice | /trees/next_biggest_node.py | 1,386 | 4.09375 | 4 | '''
Find the next biggest node in BST
'''
class Node(object):
def __init__(self, val, left=None, right=None, parent=None):
self.val = val
self.parent = parent
self.left = left
self.right = right
def next_biggest_node(node):
if not node: return None
next_biggest = None
... |
afab953163f5a177d4a6672be42410dccee286e9 | manthan787/algo-practice | /stack/sort_stack.py | 1,611 | 4 | 4 | """
Write a program to sort a stack such that the smallest items are on the top.
You can use an additional temporary stack, but you may not copy the elements
into any other data structure (such as an array).
The stack supports the following operations: push, pop, peek, and isEmpty.
"""
class Stack(object):
d... |
5914cb5245d2ead9f2b4acb76e53133f9ccdd4f2 | manthan787/algo-practice | /trees/invert_binary_tree.py | 474 | 3.984375 | 4 | class TreeNode(object):
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def invert_binary_tree(root):
if not root:
return root
root.left, root.right = invert_binary_tree(root.right), \
invert_binary_tree(root.left)... |
047ae5e4b79931546d2f577ce3e58cd521d67441 | manthan787/algo-practice | /lists/max_subarray.py | 792 | 3.65625 | 4 | """
https://leetcode.com/problems/maximum-subarray/description/
"""
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
running_sum = max_sum = nums[0]
for i in xrange(1, l... |
e7c64cadf9990089f0996a0026563b1dc096b7f9 | manthan787/algo-practice | /dp/power_sum.py | 364 | 4.1875 | 4 | '''
Find the number of ways that a given integer, X,
can be expressed as the sum of the powers of unique, natural numbers.
'''
def powerSum(x, n):
return helper(1, x, n)
def helper(i, x, n):
if i ** n < x:
return helper(i + 1, x, n) + helper(i + 1, x - i ** n, n)
elif i ** n == x:
return 1
else:
return 0
... |
12d1b337de5ee4e5d587d383de89cbf8664e7e8e | manthan787/algo-practice | /design/all_one.py | 5,162 | 3.828125 | 4 | """
Implement a data structure supporting the following operations:
Inc(Key) - Inserts a new key with value 1. Or increments an existing key by 1.
Key is guaranteed to be a non-empty string.
Dec(Key) - If Key's value is 1, remove it from the data structure.
Otherwise decrements ... |
492f8d7d3aa622d551ad0d71cf71b03128823323 | manthan787/algo-practice | /graphs/build_order.py | 1,544 | 3.921875 | 4 | """
You are given a list of projects and a list of dependencies
(which is a list of pairs of projects, where the second project
is dependent on the first project).
All of a project's dependencies must be built before the project is.
Find a build order that will allow the projects to be built.
If there is no valid... |
f58064c556806e411626a6cee52bd0187d9d3b61 | manthan787/algo-practice | /design/LRU.py | 1,488 | 4 | 4 | """
Design an LRU cache with following API:
get(key) - Return the value for the given key if it exists in the cache,
otherwise return -1
put(key, value) - Set the value `value` for given `key`. If the cache has
reached its capacity, discard the key-value added least
recen... |
87f9a1022d2e26172539d38dabb7c49c2169ada3 | Jyotishrma/python | /vowel.py | 370 | 3.9375 | 4 | #! /usr/bin/python
def main():
s=raw_input("Enter string:")
# print("your string is", +(s))
vowels=0
for i in s:
if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I' or i=='O' or i=='U'):
vowels=vowels+1
print("Number of vowels are:")
... |
636570558e5172b929676cdf9db2ae3b8c38ed80 | JeffreyHoa/legull | /analyse_url_new.py | 8,722 | 3.59375 | 4 | # Copyright 2017 Jeffrey Hoa. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
f8f66fee3d8723073bbb73949c8091c89551b614 | conzmr/Compilators | /Partial1/balanced/balanced.py | 747 | 3.53125 | 4 | import sys
import time
def main():
file = sys.argv[1]
stack = []
char_num = 0
with open(file,'r') as fileobj:
space = False
start_of_file = True
for line in fileobj:
for parenthesis in line:
if parenthesis == '(':
stack.append(pare... |
d2d00401eae270d75b4758f5623f9f2fb0f52d7f | Ganzaisme/Python-Class-code | /age_insultor.py | 454 | 3.953125 | 4 | birth_year = int(input("What year were you born in?: "))
if birth_year < 1994:
browser = input("do you remember the GOPHER? ")
if browser == 'yes' or 'y':
print("Here's your cane old man.")
else: print("You're pretty spry for an old guy")
else:
ipod = input("Did you own an iPod? ")
if ipod... |
814d82da2c8b7c8b9925eb6959cc97c5b3d74585 | mikebryant/codeeval | /113/solution.py2 | 436 | 3.546875 | 4 | #!/usr/bin/env python
from __future__ import print_function
'''
Multiply Lists
'''
import sys
with open(sys.argv[1], 'r') as test_cases:
for test in test_cases:
if not test:
continue
list1, list2 = test.strip().split('|')
list1 = list1.split()
list2 = list2.split()
... |
08d25c7530987f505253a5e546d6da34d6bd36fa | AlinaPalazuk/skillup_07_2021 | /lesson3.10/hw/home_work_threads.py | 1,689 | 3.953125 | 4 | import random
from functools import reduce
from threading import Thread, Event
from time import sleep
def generate_random_list(random_list, wait_gen_event):
"""Generate list with random (int) value."""
for _ in range(100):
random_list.append(random.randint(1, 10))
print(random_list)
wait_gen_e... |
ac036db01c57d4f29e591a051ed15b3e4be5e7a3 | Usamazafar97/PatternsUsingLoopsInPython | /5.py | 227 | 3.578125 | 4 | i=1
a=""
n=input("enter a no.")
spaces=n-1
while i<=n:
a=""
j=1
while j<=spaces:
a=a+" "
j+=1
k=1
while k<=i:
a=a+str(i)
k+=1
print a
spaces-=1
i+=1
|
9fc1bd45f3ef68b8882c5400465321b6eba76faf | Usamazafar97/PatternsUsingLoopsInPython | /11.py | 300 | 3.8125 | 4 |
i=0
row = 0
while i<31:
#if(i<3):
# if(row< 3):
# row+=1
# continue
j=0
while j<11:
if(j==row or j==11-1-row):
print "*",
else:
print " ",
j+=1
print
if(row%10==0):
row = 0
row+=1
i+=1
|
4203e2dc60d32627566d5c295b0dc4388277f611 | Kaustuvi/grove | /grove/circuit_primitives/swap.py | 3,175 | 3.890625 | 4 | """
Implementation of the swap test
Given two states existing on registers A and B, their overlap can be measured by performing a swap
test.
"""
from typing import List
import numpy as np
from pyquil import Program
from pyquil.api import QuantumComputer
from pyquil.gates import H, CSWAP, MEASURE
class RegisterSizeM... |
941834ca008d53c42dea93bc79a7fc76173c31da | binarybu9/Python | /NumpyStack/pandas/manual_data_loading.py | 342 | 3.5625 | 4 | import numpy as np
x = []
for line in open("data_2d.csv"):
row = line.rsplit(',')
sample = list(map(float,row)) # cast these string values into float
x.append(sample)
#
# for row in x:
# print(list(row)) # since x is a list of lists we can convert it into
# # a numpy array
x =... |
7ad58a052950d214d5d199b31aefb9a9a1dd5026 | binarybu9/Python | /language/Modules and import/timezone.py | 533 | 4.03125 | 4 | import time
print(time.daylight) ## if daylight returns 1 use the second string in tzname
print(time.timezone) ## timezone returns the offset from UTC and it uses non DST
print(time.tzname) ## returns a tuple containing two strings name of the
#non dst timezone and also the name of the dst timezone
if time.daylight... |
923d97f51c20a69d261b5ed40ea5e72863ff37c0 | binarybu9/Python | /language/Basics/ifchallenge.py | 240 | 4.03125 | 4 | name = input("Please enter your name and age")
age = int(input())
if 17 < age < 32:
print("Welcome to the holiday {}".format(name))
else:
print("Sorry {}, you are not old enough. Please come back in {} years".format(name,18 - age)) |
1f4fad8c46c5c90dc04ff9e93bb6a7de7deec081 | binarybu9/Python | /language/Functions/circles_challenge.py | 1,583 | 4.1875 | 4 | import tkinter
import math
#parabola function
#changing parabola to do everything
def parabola(page,size):
for x in range(size):
y = x**2 / size
plot(page,x,y)
plot(page,-x,y)
return y
def circle(page,radius,g,h):
for x in range(g,g+radius):
y = h + (math.sqrt(radius ** 2... |
b6d1504bc42873a4c7da177d40eb47a0a28b6f18 | binarybu9/Python | /NumpyStack/pandas/dataframes.py | 1,400 | 4.53125 | 5 | import pandas as pd
x = pd.read_csv("data_2d.csv",header=None) # pandas style loading data
print(type(x)) # returns a pandas Data frame
# data frames have quite useful functions
# info function
print(x.info())
# head function gives a preview of whats inside the data frame
print('*'*40)
print(x.head()) # specifi... |
c294fe74b1f2b56bc8f5a5be26f942f8fc71e7c1 | binarybu9/Python | /NumpyStack/numpy/dotproduct2_speed.py | 542 | 3.671875 | 4 | import datetime
import numpy as np
a = np.random.randn(100) # creates a random numpy array of 100 elements
b = np.random.randn(100)
T = 100000
def slow_dotproduct(a,b):
result = 0
for e,f in zip(a,b):
result += e*f
return result
t0 = datetime.datetime.now()
for x in range(T):
slow_dotprodu... |
55231f15291e17ae87491070bf9b3fdf6b516f24 | binarybu9/Python | /language/Functions/parabola_function.py | 970 | 4.0625 | 4 | import tkinter
#parabola function
def parabola(x):
y = x**2 / 100
return y
#shifting origin to center, default is top left corner
def draw_axes(canvas):
canvas.update() # to access canvas width and height
x_origin = canvas.winfo_width() / 2
y_origin = canvas.winfo_height() / 2
canvas.conf... |
2d1649a4e64e937f8fb2c99cc759225be43aaabf | jswithalex/exercises | /substring_sum.py | 362 | 4.03125 | 4 | # given a list of integers, positive and negative, find the sub-list with the largest sum
# I'm taking sublist to mean here that A is a sublist of B if every item in A is in B.
# A and B can be equal and be sublists of each other.
# brute force
l = [x,y,z]
def largest_sublist(l):
'''
great code goes here
'''
... |
c8a933ad82f403509a076a72fa7783ada8014bc5 | JoeButy/coderbyte | /intCircle.py | 227 | 3.8125 | 4 | def intCircle(r):
ans = 0
for x in range(1, int(r)+1):
for y in range(0, int(r)+1):
if x**2 + y**2 <= r**2:
ans += 1
print x, y, r
print ans
return ans*4+1
for i in range(6):
print 'r:', i
print intCircle(i) |
bf339b747e08c02b6aec2a2f2a5e3a8f38477a7e | JoeButy/coderbyte | /set_operations_to_target.py | 2,711 | 3.65625 | 4 | import itertools as iter
import random
'''
Code Fight Daily Challenge 5/3/2018:
Special thanks to @kov for this 237 idea. Here is our problem today.
Provided 5 integers a, b, c, d, e as an array and 4 basic arithmetic operations + - * /. Your mission is to identify and count all the equations that have results ended ... |
dc28b6c944e8cf8d8c451799ae445fee1f411491 | LeonOram/Iteration | /Dev Task 2.py | 301 | 3.890625 | 4 | #Leon Oram
#21-10-2014
#Dev Task 2
row_output = ""
per_row = int(input("Please enter the number of stars per row: "))
rows = int(input("Please enter the number of rows: "))
for count1 in range(per_row):
row_output = row_output + "*"
for count2 in range(rows):
print(row_output)
|
bc1daf4267ccaa205670e853c611a40879761be9 | sawrupesh04/Python | /turtle/flower1.py | 1,080 | 3.875 | 4 | import turtle
def draw_square(square_d):
for i in range(1,5):
square_d.forward(150)
square_d.right(90)
def draw_tri(triange_dr):
for j in range(1,4):
triange_dr.forward(90)
triange_dr.right(120)
def draw():
window = turtle.Screen()
window.bgcolor("sky... |
b09c13488d8b379e6508fc7123236cc86f4b9a54 | quangbk2010/SelfTraining | /MachineLearning/MLCoban/GradientDescent/GradientDescent.py | 1,197 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 25 10:57:35 2017
@author: quang
Input: f(x) = x**2 + 5*sin (x)
Ouput: find the global minimum by using Gradient descent (based on local minimum)
- More reference:
+ https://phvu.net/2012/07/08/gradient-based-learning/
"""
# To support both python 2 and python 3
fro... |
4dc9071d230def66eedd84d71d69344133864aa0 | pvankumar2410/mypythonlab | /zodiacsign (1).py | 5,060 | 3.921875 | 4 | import datetime
#from datetime
class ValueTooLargeError(Exception):
pass
def zodiac():
sign=list()
dict={
"Aries(ram)": {'UR AWESOME' },
"Taurus(Bull)": {'UR GREAT'},
"Gemini(Twins)": {'ur fantastic'},
"Cancer(Crab)": {'ur pretty talented' },
"Leo(Lion)": {'CALM AND AWESOME'},
"Vir... |
93799de692f733099c5daa5d259de7965adff663 | pvankumar2410/mypythonlab | /connect.py | 1,584 | 3.859375 | 4 | def fun():
f=1
print("-----------------------------------------------------------")
print("-\t \t\t\t \t ENGLISH LINGUIST \n\n\t\t\t\t press e to exit -")
print("-----------------------------------------------------------")
while f == 1:
words=[]
total_words=input("no of words do you wan... |
69d49190fbf416f3fa2fa065d83d7881299d7243 | harikrishnank93/hari-fullstack-development | /Python/class1.py | 357 | 3.84375 | 4 | class person:
def __init__ (self,name,age,cgpa):
self.name=name
self.age=age
self.cgpa=cgpa
student = person("aju",23,8)
print(student.name,student.age,student.cgpa)
name=raw_input("enter the name")
age=raw_input("age")
cgpa=raw_input("enter cgpa")
student1=person(name,age,cgpa)
print(studen... |
10883b3b2e2acbb6d89a15a24db557565e31410f | n26joshi/First | /a08q1.py | 1,057 | 4 | 4 | ##
##----------------------------
## Nitish Joshi (20811051)
## CS 116, Winter 2019
## Assignment 8, Question 1
##---------------------------
##
import check
## Question 1
#Q1
def invert_dictionary(d):
'''
consumes a dictionary d of the form (dictof Str (listof
Int)) and returns an inverted dicti... |
8551b5448ce16b1d4489d68b590691c8ace7b6b5 | vst/pypara | /pypara/currencies.py | 25,191 | 3.546875 | 4 | """
This module provides currency definitions and related functionality.
"""
__all__ = ["Currencies", "Currency", "CurrencyLookupError", "CurrencyRegistry", "CurrencyType"]
from collections import OrderedDict
from dataclasses import dataclass
from decimal import Decimal
from enum import Enum
from typing import Any, C... |
3181181bb50ad6ff52bc7ea2b6a5fddb11f1bd05 | SergChupin/python_basics | /lesson_7/homework_7.py | 3,392 | 3.953125 | 4 | # 1
from abc import ABC, abstractmethod # к заданию 2
print('Задание 1\n')
class Matrix:
def __init__(self, matrix_list):
self.matrix_list = matrix_list
def __add__(self, other):
for i in range(len(self.matrix_list)):
for j in range(len(other.matrix_list[i])):
se... |
0f26b34564bfcda5af0962ce6276feff0115f98d | JamieVic/py-datastorage | /uniquewords.py | 660 | 4.40625 | 4 | # This program prints and counts how many unique words are in the romeo.txt file
txt = "c:/Users/TechFast Australia/Dropbox/Programming/Python/List Exercises/romeo.txt"
uniqueWords = [] # List created to store unique words
f = open(txt, "r")
for x in f: # Loop through romeo.txt
splitWords = x.split() # Split e... |
c054fda6b70c6516f78381efddac9529716ceed3 | ZabojnikM/Python_testy | /prvni pokus tkinter.py | 345 | 3.640625 | 4 | import tkinter
from tkinter import ttk
root = tkinter.Tk()
canvas = tkinter.Canvas(root, width=256, height=256)
canvas.pack()
canvas.create_oval(20, 20, 100, 100)
canvas.create_line(0, 0, 255, 255)
canvas.create_line(0, 255, 255, 0)
canvas.create_line(10, 10, 245, 10)
canvas.create_text(50, 120, text="Hello w... |
0de79d529a0b5fd03f49a348050c3f14de11304c | laceyliang/CQL | /SQT.py | 20,160 | 4.09375 | 4 | # Python Term Project
# Chenqi Liang, Jiaqi Bai, Zhiyu Ouyang
from prettytable import PrettyTable
# transfer the students.txt file to a list
fhandle=open('students.txt')
student_all=[]
for record in fhandle:
record=record.rstrip()
record=record.split('\t')
student=[]
for info in record:
student... |
14ce504345cf6e6009de7aae444e49d8725a7b7c | mohithvegi/HackerEarth | /Input/magical.py | 1,901 | 3.9375 | 4 | # https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/magical-word/
import math
primes = [37, 41, 43, 47, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113]
def checkPrime(N):
count=0
if(N==2 or N==3):
return True
else:
... |
99fd726038a756eac70a0152c4fab43104238cb7 | mohithvegi/HackerEarth | /Input/palindrome.py | 381 | 3.890625 | 4 | # https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/palindrome-check-2/
string = input()
result = "YES"
try:
N = len(string)
for i in range(N):
if(string[i] != string[N-1-i]):
result = "NO"
break
except:
... |
1a71ae1be6c8de0f2fd7b3d06dfcf960f03f23d1 | mohithvegi/HackerEarth | /Complexity Analysis/vowel.py | 882 | 3.6875 | 4 | # https://www.hackerearth.com/practice/basic-programming/complexity-analysis/time-and-space-complexity/practice-problems/algorithm/vowel-game-f1a1047c/
vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
def Substrings(s, n):
A = []
for i in range(n):
temp = ""
for j in range(i, n):
... |
79cfb1a43eee4a2e2340a603463b6af17d686d4d | balder2046/pythonvision | /stattools.py | 809 | 3.546875 | 4 | from PIL import Image
from numpy import *
def pca(X):
""" Principal Component Analysis
input: X,matrix with training data stored as flattened array in rows
return: projection matrix (with import dimensions first). variance and mean
"""
# get dimensions
num_data,dim = X.shape
# center data
... |
24117e27c0406bcf60c7d9f097ef6c99a988d0e9 | gencyberhi/simplegame | /simplegame.py | 1,633 | 4.25 | 4 | '''\
A simple game in Python.
This program illustrates the use of several elements of Python.
'''
def init():
'''Initialize'''
print('')
print('Welcome to the simple game.')
hunger = 100
inventory = {
"apples": 3
, "bananas": 2
, "rope": 1
, "maps... |
9738a523ca11533cd1dd920858bfa0aed173b675 | bigjordon/pyton-learning | /base.py | 1,456 | 3.921875 | 4 | name = 'zhangqian'
addr = "xiao-jia-he"
age = 33
age_more = 23
# erro print(name + addr + age)
print(name + addr + str(age))
print(name + addr + "%d"%age) # could not have no () for age
print(name + addr + "%d %d"%(age, age_more))
# print add newline defaultly
# use help(print) to see print usage, int python int... |
76f21c6bf0a9b1999794c9ebe3514bd18e24a0f1 | bigjordon/pyton-learning | /basic_learn/a_projiect.py | 678 | 3.765625 | 4 | student = []
while True:
print("="*30)
print(" student management system")
print("1 add something")
print("2 del something")
print("3 mod something")
print("4 qur something")
print("5 shw something")
print("0 exit")
print("="*30)
key = input("input your selection")
if "0" =... |
3a985ae58572c5c6bfbfec825cb7683330586a19 | karthicandy/player | /complete balance or not.py | 80 | 3.53125 | 4 | k1=input()
if(k1.count("(")==k1.count(")")):
print("yes")
else:
print("no")
|
85b97465c6dd6a602a1d0c798da656503132e14e | sunwang33/code | /s14/day01/var2.py | 545 | 4.15625 | 4 | #Author: sun wang
name = input("name: ")
age = input( "age:")
job = input(" job: ")
salary = input("salary: ")
info2 = '''
-------- info of { _name } --------
Name: {_name }
Age: {_age }
Job: {_job }
Salary: { _salary }
''' .format( _name=name,
_age=age,
_job=job,
_salary=salary... |
af2c5b8f1ee9052eb32a10094e78a9e051de15fe | sunwang33/code | /s14/day01/var3.py | 268 | 4.125 | 4 | #Author: sun wang
name = input("name: ")
age = input( "age:")
job = input(" job: ")
salary = int(input("salary: "))
info3 = '''
-------- info of { 0 } --------
Name: { 0 }
Age: { 1 }
Job: { 2 }
Salary: { 3 }
''' .format( name , age , job , salary )
print(info3)
|
1428772001a15c3d93b9860149f9360a83705aed | sunwang33/code | /s14/day06/继承_门派.py | 2,297 | 3.78125 | 4 | __author__ = "sun wang"
class Organization(object):
def __init__(self,name,addr):
self.name = name
self.addr = addr
self.goldens = []
self.staffs = []
def hire(self,gold_obj):
print("雇佣了修仙者%s" %gold_obj.name)
self.goldens.append(gold_obj)
def eroll(self,sta... |
ac288ddaf05f1014cbe8c0f44a12f15c7900636f | sunwang33/code | /s14/day01/continue.py | 131 | 3.828125 | 4 | #Author: sun wang
for i in range(0,10):
if i < 3:
print ( "loop:",i )
else:
continue
print ("hehe...")
|
2c02793963cdb91f4d362c47c6b6bce51c4c3085 | pvr30/Python-Tutorial | /Object Orianted Programming In Python/class method in python.py | 1,133 | 4.15625 | 4 | """
class method:
A class method is a method which is bound to the class and not the object of the class.
They have the access to the state of the class as it takes a class parameter that
points to the class and not the object instance.
It can modify a class state that would apply across all the instances of the class... |
3d4f962e9cdce67e5c35277f2fe4520bd3284dd8 | pvr30/Python-Tutorial | /Advance Python Developement/Intresting Python Collection/deque.py | 457 | 3.8125 | 4 | """
deque : - Double Ended Queue
In a `deque`, we can push elements at the start or the end,
and we can also remove elements from the start or the end.
It is very efficient, performing very well.
"""
from collections import deque
friends = deque(('Harsh', 'Manthan', 'Sahil', 'Sanjay'))
print(friends)
friends.appe... |
c608a580c7f828428e7a3608771c1a5c6e5aea73 | pvr30/Python-Tutorial | /HackerRank Questions/Built In Functions In String.py | 767 | 4.03125 | 4 | """
s = input()
print("True") if s.isalnum() else print("False")
print("True") if s.isalpha() else print("False")
print("True") if s.isdigit() else print("False")
print("True") if s.isupper() else print("False")
print("True") if s.islower() else print("False")
print(s.isalpha())
print(s.isalnum())
print(s.isdigit())... |
18827c9d5f9e967e8b0428b4b5ec89149d3eabec | pvr30/Python-Tutorial | /Pygame/basic.py | 956 | 3.828125 | 4 | import pygame
pygame.init()
win = pygame.display.set_mode((500,500)) # this will get our window.
# This will change the window/game name
win = pygame.display.set_caption("MY GAME")
# Defining a few varibles to represent our character.
x = 50
y = 50
width = 40
height = 60
vel = 5
run = True
# main loop or game l... |
378ebc1f0ca9a3c83797c3effde84c1636021337 | pvr30/Python-Tutorial | /Advance Python Developement/Intresting Python Collection/defaultdict.py | 1,254 | 4.0625 | 4 | """
defaultdict :
The `defaultdict` never raises a `KeyError`. Instead, it returns the value returned by
the function specified when the object was instantiated.
When you need a dictionary and all keys of that dictionary
should be associated with an initial value, use `defaultdict`!
"""
from collections import defaul... |
ca4c6c3612fd18c095f1962d282d55f833e9447d | pvr30/Python-Tutorial | /Pygame/boundries_and_jumping.py | 1,456 | 3.671875 | 4 | import pygame
game_window = pygame.display.set_mode((500, 500))
pygame.display.set_caption("Boundaries And Jumping")
run = True
x = 50
y = 50
width = 40
height = 50
val = 10
isJump = False
jumpCount = 10
while run:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
... |
3dc7edb239e986f112b1e5321bf0fe7a60f806d6 | pvr30/Python-Tutorial | /Python Fundamentals/else keyword with loops.py | 432 | 4.125 | 4 | # else keyword with loops.
# On loops, you can add an `else` clause.
# This only runs if the loop does not encounter a `break` or an error.
# That means, if the loop completes successfully, the `else` part will run.
student_marks = [100,34,50,39,68,37]
for i in student_marks:
if i < 33:
print("You Are Fail ... |
a731a64707f47075f38b42fb71ec902f779e0ce4 | pvr30/Python-Tutorial | /Errors In Python/creating our own error.py | 1,651 | 4.59375 | 5 | # Creating our own errors
# Here All Error are class So we just inherit form typeerror for our own error.
"""
Sometimes it can be useful to create and raise errors with names we define,
as opposed to only using the built-in errors.
If we want to create a custom error, we can do so very easily by
subclassing the `Exc... |
68f0967af438047dfcafebec3ed0168a7c3f661c | pvr30/Python-Tutorial | /Object Orianted Programming In Python/Classes And Objects.py | 1,579 | 4.3125 | 4 | # Classes And Objects In Python
"""class Person:
pass
vishal = Person() # Here vishal is an object of Person Class.
vishal.name = "Vishal Parmar"
vishal.age = 19
print(vishal.name)
print(vishal.age) """
# self
"""Class methods must have an extra first parameter in method definition.
We do not give a value for ... |
105d73c9358afc3036a927fb435ae01b16addfef | pvr30/Python-Tutorial | /Unit Testing In Python/testing_multiplication-function.py | 1,249 | 3.796875 | 4 | from typing import Union
from unittest import TestCase
# Function Code
def multiply(*args: Union[int, float]):
if len(args) == 0:
raise ValueError("At least One Value to multiply must be passed")
total = 1
for num in args:
total *= num
return total
# Test Function Code
class TestMul... |
de88159baefd68c3b188c102b871ae5169f4cff0 | pvr30/Python-Tutorial | /HackerRank Questions/find_captains_room.py | 361 | 3.515625 | 4 |
"""
from collections import Counter
l1 = [1,5,6,7,8,9,1,5,6,8]
c = Counter(l1)
for i in c:
print(c[i])
"""
# Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import Counter
n = int(input())
group_list = list(map(int, input().split()))
c = Counter(group_list)
for i in c:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.