blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
bebc709df9b589c559bd82560412a86b753ccfdb | saskatchuwan/leetcode-problems | /python/merge_singly_linked_lists.py | 461 | 3.875 | 4 | # https://leetcode.com/problems/merge-two-sorted-lists/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
def mergeTwoLists(l1, l2):
if l1 == None:
return l2
elif l2 == None:
return l1
if (l1.val < l2.val):... |
86750125c087d65ce6c7400ba4df76571c8fa7dd | giantQQ/mystore | /myfirstgame.py | 555 | 3.5625 | 4 | import random
import sys
temp = input("猜猜我多大啦?")
guess = random.randint(0,10)
i=0
while i<3 :
if(int(temp) == guess):
print("哇塞你好牛逼啊\n")
print("你是我肚子里的蛔虫嘛")
break
else :
if(int(temp)>guess):
temp = input("哎呀猜大啦,再试试看:\n")
else :
... |
5b50e18857f8129585adf2b2c9e98996661fe546 | yangyushi/zefiia | /zefiia/notochord.py | 6,501 | 3.59375 | 4 | from . import utility
from scipy import stats
import numpy as np
import matplotlib.pyplot as plt
import scikit_posthocs as sp
def find_notochord_clusters(image, threshold, classifier, conditions, axis='y', nmax=1000):
"""
Find the clusters that belongs to the notochord using unsuperisverd
machine-lea... |
aab323baaf20de003484316d5398378013e89aec | HellMem/machine_learning | /linear_regression/v1/ep1_regression_.py | 6,595 | 3.890625 | 4 | # Coronado González, Guillermo
import random as rnd
import math as math
# Multiplies two given matrices
def multiply_matrices(mat1, mat2):
zip_mat2 = zip(*mat2)
zip_mat2 = list(zip_mat2)
return [[sum(float(element1) * float(element2) for element1, element2 in zip(row_1, col_2))
for col_2 i... |
187db225c213d22dd73c45f10acb174e665adf0e | jamchamb/chall-tools | /crypto/ohaver.py | 3,361 | 3.6875 | 4 | #!/usr/bin/env python
# ohaver.py
# Vigenere analysis with Ohaver routine
#
# Generates a list of all possible trigrams in the ciphertext and then
# determines the keys that would have been needed to reach that ciphertext
# from common plaintext trigrams. May reveal fragments of the key.
#
# `ohaver.py -h` for usage
im... |
c0238f1c64c035744472198e078c5835e7e6601b | RuiranYan/USTC-data-analysis | /exp/exp1/KeywordsSort.py | 790 | 3.5625 | 4 | # 西安电子科技大学2018考研复试
# 给定一组条数为n(n<100)的记录,记录了小明各个时期的考试成绩 ,格式为日期+成绩,中间以空格隔开,记录之间分行输入,例如:
# 2008/6/3 80
# 2009/1/1 56
# …
# 其中日期输入要求年份1996-2100,月份1-12,日期1-31。
# 现要求以分数为关键字从大到小对其进行排序,若分数相同则按日期从小到大排序。
import re
size = int(input())
st = [''] * size
l = []
for i in range(size):
st[i] = input()
st[i] = re.split('/| ', ... |
48856a50e93f8fcddbc3f6b11fefca35958b2fe1 | Jcorrales07/CalculatorPy | /calculator.py | 1,272 | 4.03125 | 4 | def add(a, b):
return a + b
def subtract(a, b):
return a - b
def divide(a, b):
return a / b
def multiply(a, b):
return a * b
def menu():
opcion = 0
while opcion < 1 or opcion > 6:
print("Que operacion quiere hacer?")
print("\t1 - Sumar")
print("\t2 - Restar")
... |
1c2298f5b8d5bb3e4f4856ace8fa3944ba14fcd2 | karlosc7/Pythonfunciones | /Ejer2_py/src/ejer7.py | 1,807 | 3.8125 | 4 | # -*- coding: utf-8 -*-
'''
Created on 26/01/2015
@author: karlosc
'''
#A mi no me da ningún fallo de identación
def Password (password):
ContieneMinuscula = False
ContieneMayuscula = False
ContieneNumero = False
ContieneAlfanumerico = False
ContieneEspacio = False
ResultadoValid... |
fe0fc1cf0cb7d9066a10be4e78bf90384ee5e5e7 | HachijoTohya/Dingus | /Hangman.py | 4,965 | 3.921875 | 4 | from Wordlist import wordlist
import random
from Wordlist import letrepl
from Wordlist import yesno
from Wordlist import Difficulty
import time
playing = True
lives = 6
diff = Difficulty()
hangword = str(wordlist[random.randrange(0, 1000)]).upper()
def playgame():
print("\nGuess the word by entering one letter a... |
33777f96cc0f17de1ca7c9045ed2850aad644249 | tieganivy3/classwork1 | /test4.py | 3,225 | 4.1875 | 4 | mylist=[]
# we are define that we need a list for student names
mylist1=[]
# we are define that we need a list for results for fractions
mylist2=[]
# we are define that we need a list for results for algebra
mylist3=[]
# we are define that we need a list for results for trigonometry
print("enter username")
username... |
d0a7ad279b5490501ea4b56619c4086dd2eec1c9 | Penoder/StudyPy | /com/penoder/chapter_1.py | 5,106 | 4.21875 | 4 | str = "Hello Python"
print(str)
str = "Python"
print(str)
arr = ["Today ", "Is ", 5]
print(arr)
arr[2] = "Monday"
print(arr)
# 集合 无序,不重复
students = {"LiHua", "HanMeiMei", "LiLei", "Tom", "Jane", "LiHua"}
# TypeError: set expected at most 1 arguments, got 4 ---> Set 集合最多一个参数
teacher = set("ZhangSan") # 等同于 teacher ... |
e708e9f3bc8dc754f3b3ca3be3fab8f7c61ea911 | baites/examples | /coding/leetcode/fb/convert_binary_search_tree_to_sorted_doubly_linked_list.py | 2,021 | 3.75 | 4 | # Definition for a Node.
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def treeToDoublyList(self, root: 'Node') -> 'Node':
def popleft(root):
# Placeholder for popped node
... |
a399d34c08d15941f294e4ea7f463b846326640f | baites/examples | /idioms/python/SpaceConstants.py | 750 | 3.546875 | 4 | #! /usr/bin/env python
def SpaceConstants():
def setattr(self, name, value):
if hasattr(self, name):
raise AttributeError(
"Cannot reassign members"
)
self.__dict__[name] = value
cls = type('SpaceConstants', (), {
'__setattr__': setattr
})
... |
ea512021557510bc3d081ece5cc3682a44b5530d | baites/examples | /coding/leetcode/principle_of_recursion/maximum_depth_binary_tree.py | 472 | 3.75 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def maxDepth(self, root: TreeNode, depth: int = 0) -> int:
if root is None:
return depth
... |
05806712ea8365ebe4b99df8e6578f678f3f587b | baites/examples | /teasers/python/lightbulbs4.py | 745 | 3.546875 | 4 | #! /usr/bin/env python
import math
NUMBER_OF_BULBS = 100
def isPerfectSQRT2(n):
x = n // 2
y = set([x])
while x * x != n:
x = (x + (n // x)) // 2
if x in y: return 0
y.add(x)
return n
def isPerfectSQRT(x):
# Trivial check
if x == 1:
return 1
# Number end... |
7845196a25c55dbe809c284c06b64f026248c36c | baites/examples | /algorithms/python/MergeSortV2.py | 687 | 3.609375 | 4 |
def Merge(A, p, m, q):
L = [A[i] for i in range(p,m)]
R = [A[i] for i in range(m,q)]
sL = len(L)
sR = len(R)
pL = 0
pR = 0
while pL < sL or pR < sR:
if pL == sL:
A[p] = R[pR]
pR += 1
elif pR == sR:
A[p] = L[pL]
pL += 1
... |
1341f52146adf48a2dfb8ea0fb60a8bebac52ede | baites/examples | /patterns/python/plugins/plugin.py | 701 | 3.625 | 4 | """Define a plugin as python abc class."""
import abc
import logging
import time
class Plugin(abc.ABC):
"""Implement plugin abstract class."""
def __init__(self):
"""Class constructor."""
classname = self.__class__.__name__
self.logger = logging.getLogger(classname)
self.logge... |
77060943c42fadc1f0f4bf77ff5bf3690e63d0e0 | baites/examples | /algorithms/python/BubbleSort.py | 349 | 4 | 4 | #! /usr/bin/env python2
def BubbleSort(a):
flag = True;
while flag:
flag = False
for i in range(len(a)):
if i+1 < len(a) and a[i] > a[i+1]:
tmp = a[i+1]
a[i+1] = a[i]
a[i] = tmp
flag = True
a = [5, 2, 4, 6, 1, 3, 9, 4,... |
6634553d2ace5b0a434d37facbab11fbb2c31590 | baites/examples | /algorithms/python/PairSum.py | 847 | 3.90625 | 4 | #! /bin/env python
def PairSumSort(A, x):
A.sort()
i = 0
j = len(A) - 1
while i<j:
s = A[i]+A[j]
if s == x:
print('Pair found [{},{}] with sum {}'.format(
A[i], A[j], x
))
return
elif s > x:
j -= 1
else:
... |
2820a2eb348d51a517665884398cbf1a04984f8b | baites/examples | /coding/careercup/q5702735421243392.py | 1,261 | 3.78125 | 4 |
class Node:
def __init__(self, value):
self.value = value
self.prev = None
self.next = None
class DictWithLast:
def __init__(self):
self._map = {}
self._tail = None
def set(self, key, value):
node = Node(value)
if self._tail is None:
sel... |
ce6552bee546134bc0c7159deb3d277b046d962b | baites/examples | /coding/leetcode/az/binary_tree_zigzag_level_order_traversal.py | 729 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
values = {}
def c... |
87c206119877fe81dbb1a0328c2ab63525707432 | baites/examples | /coding/leetcode/problems/longest_palindromic_substring_hashing_v2_stress.py | 5,386 | 3.8125 | 4 |
import random
class Naive(object):
def _isPalindrome(self, string, begin, end):
"""Verify if substring is a palindrome."""
while end > begin:
if string[begin] != string[end]:
return False
begin += 1
end -= 1
return True
def longestP... |
e112741491f4929e2ae4ad94d57ca049c35ac577 | baites/examples | /coding/contribs/merge-sort-map/merge_sort_map_stress.py | 3,624 | 3.796875 | 4 |
class Naive(object):
def mergeSortMap(self, A, B, n):
AB = A + B
AB.sort()
S = len(AB)
# Sanity check
if n < 1 or n > S:
raise IndexError('merge-sort map index out of range')
return AB[n-1]
class Solution(object):
def isNotHeadTailCondition(self, ... |
971ec0546790131a91222958eb34ebf42aed820b | baites/examples | /coding/leetcode/az/implement_strStr_rabin-karp.py | 1,595 | 3.515625 | 4 | class Solution:
def strStr(self, haystack: str, needle: str) -> int:
# Mersenne prime
# https://en.wikipedia.org/wiki/Mersenne_prime
prime = 2^31-1
base = 31
h_size = len(haystack)
n_size = len(needle)
def get_hash(word):
value = 0
p... |
41651e7a4220654df0e967daf658a38a5538e3ce | baites/examples | /coding/leetcode/fb/validate_binary_search_tree.py | 1,303 | 3.921875 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
@staticmethod
def inorder_check(root, condition):
if root is None:
return True
chec... |
1d783de5fe14ad7a2bde2669685bc15b4e1b7161 | baites/examples | /coding/careercup/q5767478026698752.py | 1,240 | 3.75 | 4 | from collections import deque
def bfs(adj, u):
dist = [-1]*len(adj)
prev = [None]*len(adj)
thenode = u
dist[u] = 0
queue = deque()
queue.appendleft(u)
while len(queue) > 0:
u = queue.pop()
for v in adj[u]:
if dist[v] == -1 or dist[v] == 0:
dist[v]... |
66f112f7512c88ae10244eda911deeb8f6ff70cd | baites/examples | /coding/careercup/q5710647581474816.py | 2,366 | 3.625 | 4 | class BTNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
class BSTree:
def __init__(self):
self.root = None
@staticmethod
def _find(key, node):
if node.key == key:
return key
elif node.key > key:
i... |
635b244ec0c1287cfb9a8bb6832da3ae43d7c09e | baites/examples | /coding/leetcode/problems/two_sums_v2.py | 512 | 3.53125 | 4 | # https://leetcode.com/problems/two-sum/
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
tmp = { target - nums[i]: i for i in range(len(nums)) }
for j in range(0,len(nums)):
... |
baba7a0a82108b516215496f17963c153868df8e | baites/examples | /coding/leetcode/az/min_stack.py | 714 | 3.65625 | 4 | class MinStack:
def __init__(self):
self._stack = []
self._stack_min = []
def push(self, val: int) -> None:
self._stack.append(val)
if len(self._stack_min) == 0 or val < self._stack_min[-1]:
self._stack_min.append(val)
else:
self._stack_min.appen... |
21f8d939bd30d3089715a96c2fa8483188b8c361 | baites/examples | /coding/leetcode/az/lru_cache.py | 695 | 3.609375 | 4 |
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
self._cache = OrderedDict()
self._capacity = capacity
def get(self, key: int) -> int:
if key in self._cache:
self._cache.move_to_end(key)
return self._cache[key]
els... |
ab630a917b740490bff2b3610a9e5015dc70195b | baites/examples | /algorithms/python/BinarySearchTree.py | 3,017 | 3.515625 | 4 |
class BTNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
class BSTree:
def __init__(self):
self.root = None
@staticmethod
def _find(key, node):
if node.key == key:
return key
elif node.key > key:
... |
77d1835e979c6c00cec0fa9ef591a5bb2f506203 | baites/examples | /coding/codeforces/contests/1328/kth-beautiful-string/kth-beautiful-string.py | 1,122 | 3.84375 | 4 | import sys
# The solution is based on mapping different
# string combinations as indices of a off-diagonal
# lower triangular part of a matrix.
# j
# 1 2 3 4 5
# 1 | x
# 2 | 1 x
# i 3 | 2 3 x
# 4 | 4 5 6 x
# 5 | 7 8 9 10 x
#
# So for example the 8th string of size 5 is located
# in... |
2fd510a7f25dcd5da806ff7617a3ba89e4cffe34 | baites/examples | /coding/leetcode/az/word_ladder_v2.py | 1,209 | 3.609375 | 4 | class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
size = len(beginWord)
neighbors = defaultdict(list)
for word in wordList:
for index in range(size):
neighbors[word[:index] + '*' + word[index+1:]].append(word)
... |
b1d9ae663dc750c2ed06ba22f5a44a7243cdfd5b | wangxianghust/Xapian-search | /project/client/client_format.py | 174 | 3.71875 | 4 | def input_format(string):
string.replace(' ','$')
#ret = ''
#for item in argv_list:
# ret = ret + item + '$'
#return ret[:len(ret)-1]
return string
### END of function |
ffecb7b7dcebecb9b21d1bb0e149ec1a5232b9ba | DucTranVan/linear-layer | /linear.py | 1,689 | 4.125 | 4 | def linear_transform_py_list(weight_matrix, data):
"""
The linear transform function implement using python data structure.
Input is multiple vectors, represented by a matrix which each row is an sample.
Output is a matrix which each row represents transform result for each sample,
each colum repres... |
ce2ac242968969f024af59a7a5bb3db860c1b735 | liuuu/python-algorithm | /5.first_last_in_list.py | 2,190 | 3.5 | 4 | import time
class Solution:
def firstLastInList(self, nums, target):
first = self.binarySearch2(nums, 0, len(nums) - 1, target, True)
last = self.binarySearch2(nums, 0, len(nums)-1, target, False)
return [first, last]
def binarySearch(self, nums, low, high, target, isFirst):
index = None
whil... |
02487a272ba0b4a0f91f10316faa526cbcb5c691 | jschaf/Tetris-Math | /board.py | 4,558 | 4 | 4 | '''A game board for equations.
'''
import random
from equation import int_from_digits, Equation
class Board(object):
'''A board to hold the game state. Equations start at the top
(defined as 0) and progress down the screen at the rate defined by
drop_speed. When the equation hits the bottom or the stack ... |
1223bd5a64361263f9a6fb8fa5b0bb1cb1daa478 | hashtagallison/Python | /Practice_STP/Examples_Notes/Ch6.1_STP.py | 3,959 | 4.25 | 4 | # https://www.theselftaughtprogrammer.io
# Cory Althoff - The Self-taught Programmer
# Chapter 6.1 pg 87 - String Manipulation
# hashtagallison - Practice 2019-04-08
#-------------------------------------------
#-------------------------------------------
# EXAMPLE: pg 87
#-------------------------------------------... |
c1aaa720a88e10787b85c07da689cfc5f4c44cbe | hashtagallison/Python | /Practice_STP/Examples_Notes/Ch3.2_STP.py | 2,697 | 4.46875 | 4 | # https://www.theselftaughtprogrammer.io
# Cory Althoff - The Self-taught Programmer
# Chapter 3.2 pg 35 - Statements
# hashtagallison - Practice 2019-04-05
#-------------------------------------------
# TIP---> Conditional statements: if, elif, else
# > Control structure: a block of code that ma... |
cc7e5b39a07185268983123a77426be05e885099 | hashtagallison/Python | /Practice_STP/Examples_Notes/Ch3.1_STP.py | 6,852 | 3.78125 | 4 | # https://www.theselftaughtprogrammer.io
# Cory Althoff - The Self-taught Programmer
# Chapter 3.1 pg 13 - Intro to Programming
# hashtagallison - Practice 2019-04-04
#-------------------------------------------
#-------------------------------------------
# EXAMPLE: pg 13
#-------------------------------------------
... |
2aef341321be8d49c5659e7d09cede05d9f28952 | chelli-s/programming_lab | /intro.py | 464 | 3.625 | 4 | def list_sum(the_list):
somma=0
for item in the_list:
somma = somma + item
print('Somma: {}'.format(sum))
print(list_sum([1,4,10]))
try:
from datetime import datetime
my_date = datetime.strptime(elements[0] , '%d-%m-%Y')
except Exception as e:
... |
7125c5952f6c4d3f706cd449290400faa94174b0 | slamdunk0414/LearnPythonHardWay | /24-更多练习.py | 568 | 3.640625 | 4 |
print ("试着打印一些东西")
poem = """
常记溪亭日暮,沉醉不知归路,
兴尽晚回舟,误入藕花深处。
争渡,争渡,惊起一滩鸥鹭。
"""
print("----------")
print(poem)
print("----------")
six = 4 + 3 - 5 + 4
print ("这就是六:%d"%(six))
def hero(started):
power = started * 50
iq = power / 20
agile = power / 10
return power,iq,agile
start = 2
power,iq,agil... |
64b335941d631262b54b75532bb04187eee0e8f5 | andrewmccullough/CS1111 | /07quadratic.py | 964 | 3.546875 | 4 | # Andrew McCullough (asm4wm)
import math
def big_root (a, b, c):
# Returns the larger root of the equation.
try:
# Wraps the root calculations in a "try" statement to protect from equations without real solutions.
root1 = (-b + math.sqrt(b ** 2 - 4 * a * c)) / 2 * a
root2 = (-b - math... |
b64d589982108905b204d93fc33b10fbc29e3c12 | rawrgulmuffins/presentation_notes | /pycon2016/tutorials/measure_dont_guess/handout/measuring/clock_check.py | 884 | 3.5 | 4 | """Checking different timing functions.
"""
from __future__ import print_function
import os
import sys
import time
import timeit
if sys.version_info.major < 3:
range = xrange
def clock_check(duration=1):
"""Check the measured time with different methods.
"""
start_os_time0 = os.times()[0]
star... |
581e50dfff013689c0a259c71f082e94ea8e2985 | sup/pydata | /pydata/DataStructures.py | 10,686 | 3.625 | 4 | #datastructures.py
#Charles J. Lai
#July 13, 2013
"""
==============
datastructures
==============
This module contains both implementations of common abstract data types as
well as "helper" data structures for different implementations including
linked nodes and tree cells.
If the class name of the ADT implementatio... |
e78e6840b507b9392940f1db36e4f30dad4ef7c7 | shriki001/Operating-Systems | /Python/HomeWork/ex1.py | 4,356 | 4.125 | 4 | # OS2 Python Programming 2018b
#
# File:ex1.py
# ==============================================================================
# Writen by: Michael Shrik, Kfir Matityahu
#
# Run: ex1.py using Python interpreter
#%%--------------------------------------------------------------------------%%#
"""
Exercises 1: print... |
6cd5b44740b21b1a145ac3c261ff8e6d9a7d8d49 | kocsenc/kchung | /Python/StringProblems/FirstNonRepeating.py | 1,531 | 3.859375 | 4 | import unittest
__author__ = 'Kocsen'
# Kocsen Chung
# Problem from previous interview
# Implement an algorithm that will determine which is the first element in a string that does not repeat itself ever
def first_non_repeat_of(str):
# Method will go through string and construct dictionary of counts
count =... |
d064335178c9da5908e31afbffaac869a8b8d2f6 | CristinaMarzo/PrimeraEvaluacion | /Python/Calculadora ecuaciones segundo grado 2.py | 558 | 4.03125 | 4 | import math
print('Teniendo en cuenta la ecuacion del tipo ax^2+bx+c:')
print('----------------------------------------')
a=int(input('Introduce el valor de a: '))
b=int(input('Introduce el valor de b: '))
c=int(input('Introduce el valor de c: '))
#Calculamos el discriminante
d=(b*b)-4*a*c
#Comprobamos ... |
e99f43a961f012513902942d4d9c59944aa96620 | CristinaMarzo/PrimeraEvaluacion | /Python/Ecuacion de segundo grado_clase.py | 610 | 3.90625 | 4 | #En este programa le pedimos al usuario
#que teclee los coeficientes de un polinomio
#y hallamos el valor de las raices.
import math
def ecuacion():
print "Introduzca los coeficientes del polinomio"
print "El polinomio es a*x^2+b*x+c"
a=input("a= ")
b=input("b= ")
c=input("c= ")
ra... |
e590598eba6896c9d1e433039e4be3ba0e144f8f | CristinaMarzo/PrimeraEvaluacion | /Python/Piramide 1 Antonio.py | 373 | 3.8125 | 4 | def piramide():
filas = 8
espacios = ' '
asteriscos = '*'
for i in range(filas):
for espacios in range (1, filas-i-1):
espacios = espacios + ' '
for asteriscos in range (1, 2*i):
asteriscos = asteriscos + '*'
print espacios + asteriscos
e... |
d6dda63ac78d22a534373b6ac9d4da06a0af4d81 | BjornChrisnach/intro_to_python_UTA_Arlington | /def_distance_betw_2_points.py | 934 | 4.0625 | 4 | # Write a function that finds the distance between two points and returns it.
# The distance between two points with x,y, and z components can be calculated as:
# distance=(x2−x1)2+(y2−y1)2+(z2−z1)2 The input for this function will be two 1
# Dimensional lists that contain the x,y,z coordinates each.
import math
def ... |
e5c29319c32429bac52e7d43a524bc36b83b1947 | BjornChrisnach/intro_to_python_UTA_Arlington | /def_unit_vector.py | 909 | 4.46875 | 4 | # Write a function that normalizes a vector (finds the unit vector).
# A vector can be normalized by dividing each individual component
# of the vector by its magnitude. Your input for this function will
# be a vector i.e. 1 dimensional list containing 3 integers.
def normalize_vector(vector):
result = []
x = v... |
3e18893f3e3fc63efbadcef420e54ba511b65204 | BjornChrisnach/intro_to_python_UTA_Arlington | /def_monthly_payments.py | 1,043 | 3.9375 | 4 | # Write a function that calculates and returns the monthly payments
# for a loan. This function accepts three parameters in the exact order
# (principal, annual_interest_rate, duration):
def calculate_monthly_pay(principal, annual_interest_rate, duration):
interest_rate = (annual_interest_rate / 100) / 12
amoun... |
e9b7ca68844f7d2842898f340fe0101a46c60345 | torchontf/Test-File-Example | /sample_tests_example.py | 2,117 | 3.90625 | 4 | # import * from program file where code is written
import unittest # can do this within any Python file -- it's in the standard library
# Let's say I have a code idea --
# I'll define a class Beverage
# I'll also define subclasses of Beverage: Coffee, and Milk
# And I know that after my code is run, a special menu fil... |
cd0d809b1df8c87e45baa0023524d50f68ab57b2 | mary7ray/Task4-10 | /numm10.py | 3,228 | 3.765625 | 4 | from math import pow
class complex_numbers:
def __init__(self,real,imagin):
self.real = real
self.imagin = imagin
def __add__(self,other):
return complex_numbers(self.real + other.real, self.imagin + other.imagin)
def __sub__(self,other):
return complex_numbers(self.real -... |
9d16b3d1ed9521b1f23df7f79d5d38104f369611 | Dhivyadarsshni/dhivyadarsshni-mycaptain-proj3 | /strings_values.py | 638 | 4.21875 | 4 | String=input("Please enter a string: ") #taking a string as input
def most_frequent(string): #defining a function with 'string' as parameter
alpha=dict() #creating a empty dictionary
for key in string:
'''
checking the condition:
if the fir... |
48643696961cc2d9e849e341a06dbecf1e0e1410 | AljosaZ/Simple-calculator | /simple_calculator.py | 1,677 | 4.125 | 4 | print("Welcome to my simple calculator! \n")
count = 0
while True:
if count == 6:
print("\nWas that really that hard?")
quit()
else:
try:
x = float(input("Please enter the first number: "))
break
except ValueError:
print("Please choose a numbe... |
4de94207feafa52f88fb44e2ee0aa1d9f2a224df | prd-hai-huynh/python-101 | /5.2-del.py | 269 | 3.734375 | 4 | words = ['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
# remove the first element
del words[0]
print(words)
# remove the slices from a list
del words[1:5:1]
print(words)
# clear the entire list
del words[:]
# del entire variables
del words
|
0eb81267f7a5f66377ab3cf29db7ccdf8f89a6fe | prd-hai-huynh/python-101 | /3.1.2-strings.py | 323 | 3.84375 | 4 | print('This is a single line string')
print('This is a 2-line\nstring')
print('''\
this is a paragraph
line 2
line 3
...
line n
''')
print('this is a formatted string with param1: {} and param2: {}'.format('1', 2))
print('this is a capitalized string'.capitalize(... |
16b8666df0d0e2abac70a706b961cc7f0a81d415 | arivon/python-learn | /Students.py | 617 | 3.921875 | 4 | #!/usr/bin/env python3
n = int(input("please input number of students:"))
#建立一个存储数据的字典变量
data = {}
subjects = ('Physics','Math','History') #所有科目的列表
for i in range(0,n):
name = input("please input name of student {}:".format(i+1)) #输入第i+1个同学的名字
marks = []
for x in subjects:
marks.append(int(input("En... |
adc022382f49de8d0d58d327abfa4bf48080c3c0 | lucyowusu/Lab_Python_01 | /Userinput.py | 375 | 3.96875 | 4 | print 'Exercise 4'
print ''
fName =raw_input('Please enter your FirstName: ')
lName =raw_input('Please enter your LasttName: ')
print ''
print ''
print "Please enter your Date of Birth: "
print ''
month =raw_input('\tMonth? ')
print ''
Day =raw_input('\tDay? ')
print ''
Year =raw_input('\tYear? ')
print ''
print ''... |
d3bc32ef884ed359ff9cb10d2b5e066bc1031e9e | premlatha/Python-for-Everybody-Specialization-Course-from-Coursera | /Using Python to Access Web Data/regularexpression.py | 161 | 3.640625 | 4 | import re
s='i am new to regularexpression'
e=re.findall('[0-9]+',s)
print(e)
x = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'
y = re.findall('\S+?@\S+', x)
print(y) |
6f1dea25e167d70507cf442af6d0c4854c9e1a4a | premlatha/Python-for-Everybody-Specialization-Course-from-Coursera | /Python Data Structures/assignment9-5.py | 489 | 3.5625 | 4 | fname=input('Enter filename:')
try:
fh=open(fname)
emails=dict()
for line in fh:
if line.startswith('From') and not line.startswith('From:'):
name=line.split()
email=name[1]
emails[email]=emails.get(email,0)+1
except:
print('File not found')
maxcountvalue=0
fo... |
89690fd7adfd418e345d4a744c7ca08463e1ec73 | andrewkho/aoc2020 | /quicksort/run.py | 744 | 3.671875 | 4 | import fire
from typing import *
from dataclasses import dataclass, field
import numpy as np
def quicksort(A, l, r):
if l < r:
p = pivot(A, l, r)
quicksort(A, l, p-1)
quicksort(A, p+1, r)
def pivot(A, l, r):
p = (l+r)//2
print(p)
while True:
while A[l] < A[p]:
... |
86bbbb5b85b893386b392161b1943bfae18d40de | amylfrazier/learn-python | /hw1/main.py | 948 | 4.0625 | 4 | def main():
print("What is your first name?")
myFirstName = input()
print("What is your last name?")
myLastName = input()
print("How old are you in months?")
myAgeMonths = input()
print("What is your favorite color?")
myColor = input()
print("Where were you born?")
myBirthPlace =... |
ba095689d01950df0a35115e71d899ffd00e3f6b | amanraj22011/amanraj | /str_formatting.py | 318 | 4.21875 | 4 | name ="AMAN RAJ "
age = 23
print("hello " + name + " your age is " + str(age))
# string formatting
# python 2
# python 3
# python3.6
print("hello {} your age is {}".format(name, age)) # pyhton 3
print(f"hello {name} your age is {age}") # python 3.6
print("hello {} your age is {}".format(name, age + 2)... |
1740b67b44ace6ce051e5778cfb8974c66e0c024 | sv18445/test | /test.py | 189 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 10 10:47:59 2018
@author: sv18445
"""
for i in range(5):
print("Hello", i,"!")
print("Goodbye", i+1)
print("this is my extra change")
|
d76db0ede3a13a6ba2e1e2170ba627fe4e50f26d | Nagappansabari/PythonPrograming | /player/commancharacter.py | 198 | 3.5 | 4 | x=raw_input()
y=raw_input()
n1=len(x)
n2=len(y)
count=0
for a in range(0,n1):
for b in range(0,n2):
if x[a]==y[b]:
count+=1
if count!=0:
print "yes"
else:
print "no"
|
70ebbcfed01b409f8042e3c5f4b6caeaa47ff5eb | Nagappansabari/PythonPrograming | /beginner/numberofdigitsininteger.py | 60 | 3.5 | 4 | integer=input("enter the integer")
print len(str(integer))
|
c26574abbc985c70beaab9e774bf60c8692cb9f3 | Nagappansabari/PythonPrograming | /printifitisholiday.py | 84 | 3.84375 | 4 | x=raw_input()
y=x.lower()
print y
if y=="sunday" or y=="saturday":
print("yes")
|
1818dd1928c82d617a8baa685152dddd3727176e | santamariagio/rule110 | /rule110.py | 1,378 | 4.03125 | 4 | def rule_110(gen, next_gen, i):
"""
Applies the rule 110 cellular automaton to the given generation.
The rule_110 function takes two lists and a number `i`,
corresponding to the position in the two lists, and returns a
list. The list `gen` is kept unmutated whereas the list
`next_gen` could be... |
ffee44fb680e3cfc29a4df1aba6819e3fac8f41e | GregChung-IBFL/image2excel | /image_converter.py | 14,765 | 3.546875 | 4 | """
Processing module for image2excel. Handles one image file end-to-end.
To use, instantiate a Converter, then call its process_file method. A
Converter is for single-use only, use a new Converter to process another image.
Coded by Greg Chung : https://github.com/GregChung-IBFL/image2excel
"""
import os
from dateti... |
0d6904b819e826865d2fa6b171d3a922aad4dfc2 | brandonmpetty/Doxa | /Demo/Python/demo.py | 1,058 | 3.578125 | 4 | from PIL import Image
import numpy as np
import doxapy
def read_image(file):
return np.array(Image.open(file).convert('L'))
# Read our target image and setup an output image buffer
grayscale_image = read_image("2JohnC1V3.png")
binary_image = np.empty(grayscale_image.shape, grayscale_image.dtype)
# Pick an algor... |
44dda5de7f69e13e55583f09ac4f07bcfca813a3 | SharonReginaSutio99/Python-basic | /prac_04/lists_exercises.py | 1,104 | 4 | 4 | """
Name: Sharon Regina Sutio
Link: https://github.com/SharonReginaSutio99/cp1404practicals
"""
def main():
basic_operations()
username_checker()
def username_checker():
usernames = ['jimbo', 'giltson98', 'derekf', 'WhatSup', 'NicolEye', 'swei45', 'BaseInterpreterInterface',
'BaseStdIn... |
37999a541f01d585363a07fe5738a9d642981590 | SharonReginaSutio99/Python-basic | /prac_05/emails.py | 1,340 | 4.40625 | 4 | """
CP1404/CP5632 Practical
Store user's emails and names.
Name: Sharon Regina Sutio
Link: https://github.com/SharonReginaSutio99/cp1404practicals
"""
def get_name(email):
"""Separate name from email."""
possible_name = email.split("@")[0]
full_name = ""
names = possible_name.split(".")
for name i... |
460adf423ed6397885b365a26095a7d80cdfc40d | 5l1v3r1/Examples-4 | /Qiskit/Adder_Circuit.py | 2,809 | 3.625 | 4 | from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute
from qiskit import BasicAer
'''
APItoken="APItoken"
config = { "url": 'https://quantumexperience.ng.bluemix.net/api'}
'''
n1 = input("Enter a binary number with less than 8 di... |
c122b4f16c08a2466fc14b0c8b7d82869d8fd0b4 | shawnk3/python | /rectinterface.py | 465 | 3.71875 | 4 | # write your solution to Exercise W10.T03 here
# import in the matplotlib module
import numpy as np
# inport in the OpenCV module
import cv2
# open camera/capture image
cam = cv2.VideoCapture(0)
_,img = cam.read() # read image from camera
cam.release() #release (close) camera
# draw rectangles of different colors on... |
e1ede857b59fb087e2595e491e5df6bdbe08123d | chuguant/Data-Services-Engineering | /Ass1/z5145006_ass_1.py | 4,945 | 3.703125 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from collections import defaultdict
def clean(dataframe):
for i in dataframe:
i.replace(' ','')
# new_date = dataframe['Date of Publication'].str.extract(r'^(\d{4})', expand=False)
# new_date = pd.to_numeric(new_date)
# new_... |
38253dfba58f8727bd5a1b6c0f8d56e32d515cbb | PrestonSo4/PythonChallenges | /BusCounter/busCounter.py | 697 | 4.09375 | 4 | #https://www.101computing.net/school-trip-bus-quote/
# Large Bus: $360 Small Bus: $140
smallBus = 140
bigBus = 360
sBLimit = 16
bBLimit = 46
def calculateBus():
students = int(input('Enter the number of students: '))
staff = int(input('Enter the number of staff: '))
participants = students + staff
bigBu... |
e675026dddd91c3d492c546f5646950777669fda | PrestonSo4/PythonChallenges | /Poker Die/RollingDice.py | 478 | 3.90625 | 4 | import random,time
from random import randint
def roll():
die1 = random.randint(1,6)
die2 = random.randint(1,6)
die3 = random.randint(1,6)
print("Die 1:", die1)
print("Die 2:", die2)
print("Die 3:", die3)
if die1 == die2 and die2 == die3:
print('You got a three of a kind!')
elif ... |
1a741f66aade3f209103b05ded236679ebb03dab | PrestonSo4/PythonChallenges | /Pentagram Challenge/pentagram.py | 1,149 | 4.375 | 4 | #www.101computing.net/pentagram-challenge/
#https://replit.com/@PrestonSo4/Pentagram-Challenge-1#main.py
#if you want to see the code in action click above to the repl.it link
import turtle, math
myPen = turtle.Turtle()
myPen.speed(209)
myPen.shape("arrow")
myPen.pencolor("purple")
myPen.pensize(2)
myPen.speed(1000)
de... |
81ee9d42a6fe7f3b920a6846a526ca625565adcf | PrestonSo4/PythonChallenges | /Color Differences/Color Diff.py | 1,168 | 3.59375 | 4 | global colorWheel
import math
colorWheel = []
colorWheel.append(["Red",255,0,0])
colorWheel.append(["Orange",255,127,0])
colorWheel.append(["Yellow",255,255,0])
colorWheel.append(["Chartreuse Green",127,255,0])
colorWheel.append(["Green",0,255,0])
colorWheel.append(["Spring Green",0,255,127])
colorWheel.append(["Cyan"... |
0728924b76d83a905e444d1eca104bbe430865af | DavidGrifoGimeno/Algoritmia | /Pràctiques/Introduccion/ej2.py | 252 | 4 | 4 | entero=int(input("Introduce enteros. Un número negativo para acabar: "))
lista=[]
while entero>=0:
lista.append(entero)
entero = int(input("Introduce enteros. Un número negativo para acabar: "))
lista.sort()
for elem in lista:
print(elem) |
02e4e31384d3c567d63d30956baef5f51a201ed1 | dangreenberg100/coin-flipper | /main.py | 431 | 3.65625 | 4 | import random
active: bool = True
while active:
print("Welcome to the coin flipper")
print("---------------------------")
value = random.randint(1, 2)
if value == 1:
print("You landed on Tails\n")
if value == 2:
print("You landed on Heads\n")
statement = input("Would you like to... |
9d1b1c957068d30f6ecd90fcd48d665253072619 | cecilia-cc/Algorithm | /LinkedList/odd even linked list merge.py | 2,682 | 3.75 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def oddEvenMerge(self,head):
head1, head2 = self.devide(head)
head2 = self.reverse(head2)
head = self.merge(head1,head2)
self.printList(head)
return head
def dev... |
50e7b75355ee2918cd426dde79f3c6d8be0de486 | cecilia-cc/Algorithm | /Sorting/InsertionSort.py | 640 | 4.28125 | 4 | def InsertionSort(nums):
"""
left | right
第一个元素不动 每次选中右边第一个元素插入左边
左边shift找到插入的位置
Time complexity: worst/O(n^2) ; avg/O(n^2) ; best/O(n) ;
Space complexity: O(1)
Stable
:param nums: unsorted array
:return: sorted array
"""
for i in range(1,len(nums)):
temp = nums[i]
... |
5f624c2e979b12e3ba9315f8a62254c79ec3fa45 | cecilia-cc/Algorithm | /Sorting/MergeSort.py | 841 | 4.15625 | 4 |
def MergeSort(nums):
"""
Divide and conquer
将有序的子序列合并,得到完全有序序列。
Time complexity: worst/avg/best/ O(nlogn)
Space complexity: O(n)
Stable
:param nums: unsorted array
:return: sorted array
"""
# 递归法
if len(nums) <= 1:
return nums
mid = len(nums) // 2
left = n... |
627e6ac8047457faf98e8ec38237c3fd991c5284 | cecilia-cc/Algorithm | /Trie/prefix-trie-2.py | 1,247 | 3.625 | 4 | import collections
import sys
class TrieNode:
def __init__(self):
self.children = collections.defaultdict(TrieNode)
self.weights = set()
class WordFilter(object):
def __init__(self, words):
self.words = words
self.root = TrieNode()
for word in words:
self.a... |
58da7367a2415a7626c3d7931713f17f650ebe97 | soham-chitnis10/ERC-assignment | /XOR Neural Network.py | 2,332 | 3.859375 | 4 |
import numpy as np
import matplotlib.pyplot as plt
def sigmoid (x):
return 1/(1 + np.exp(-x))
def sigmoid_derivative(x):
return x * (1 - x)
inputs = np.array([[0,0],[0,1],[1,0],[1,1]])
expected_output = np.array([[0],[1],[1],[0]])
epochs = 11000
lr = 0.1
inputLayerNeurons, hiddenLayerNeurons, outputL... |
dab252939f05aff9785b29bbb181174314523740 | jjmirandaa86/learn_Python | /example2/5.list.py | 480 | 4.125 | 4 | my_list = ["Hola",15,34.5,True]
print(my_list)
my_list.append(6) #Add new records
print(my_list)
my_list.insert(1, "en campo 1") #Add new records in possition definite
print(my_list)
print(my_list[1])
my_list.remove(15) #remove element than it's with data 15 (integer)
print(my_list)
my_list.pop() #remove last elemen... |
17163b655c772435657fd74f7a135fafbe26906a | jjmirandaa86/learn_Python | /example2/X17.decoradores.py | 1,083 | 3.921875 | 4 | # agrega mayor funcionlidad
# funcion que crea funciones
# por lo menos deben hacer 3 funciones // my_decorator / func / wrapper
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is c... |
8f18079dc21c671187b8b13ebf46f107a1bf2970 | jjmirandaa86/learn_Python | /example/4_variables_list.py | 1,230 | 4.09375 | 4 | demo_list = [1, "hola", 5.5, True, [1,2,3]]
colores = ["blanco", "azul", "negro", "rojo"]
number_lis = list ((1,2,3,4))
print(number_lis)
# crear lista en secuencias
r = list (range(-1,100))
print(r)
# que puedo hacer con una lista
print(dir(colores))
print(len(colores)) # cuantos elementos hay
print(co... |
fdcbb54e8a2910def38de933332d9505ff1eb7d0 | jjmirandaa86/learn_Python | /example2/9.ciclos.py | 249 | 3.84375 | 4 | #While
variable = 0
while variable < 10:
variable += 1
print(variable)
if variable == 5:
print("llego al 5")
continue
if variable == 8:
print("llego al 8 y terminara")
break
else:
print("termino") |
47b0407de17c352f0cc2d1c9723bed3d7dd2f8ac | midnightkali/Bro-Code-Youtube- | /Python Course/Python multiple assignment 🔠.py | 452 | 4.03125 | 4 | # Multiple assignment = allows us to assign multiple variables at the same
# in one line of code
# # Regular Way
# name = "Bro"
# age = 21
# attractive = True
#
# # Shortcut
# name, age, attractive = "Bro", 21, True
# print(name)
# print(age)
# print(attractive)
# # Regular Way
# Spongebob = 30
# Patrick = 30
# Sand... |
6d688697c107e097d7550632028d0c2f8861b263 | chlxry/cp2019 | /practical_1/q1_fahrenheit_to_celsius.py | 456 | 4.46875 | 4 | # Write a program q1_fahrenheit_to_celsius.py that reads a Fahrenheit degree in double (floating point / decimal) from standard input
# then converts it to Celsius and displays the result in standard output
# The formula for the conversion is as follows: celsius = (5/9) * (fahrenheit - 32)
fahrenheit = float(input("In... |
22ef7ace60f0e3b1d45ccf4a2484f06a1f1b2da4 | chlxry/cp2019 | /practical_4/q7_find_largest.py | 227 | 4.15625 | 4 | # Write a recursive function find_largest(alist) that returns the largest integer in an array alist.
# For example, given alist = [5, 1, 8, 7, 2], sum_digits(alist) returns 8.
def find_largest(alist):
print(max(alist))
|
977d37bb35cd9184d62b082ecc683299c0505acb | chlxry/cp2019 | /practical_4/q4_print_reverse.py | 360 | 4.4375 | 4 | # Write a recursive function reverse_int(n) that reverses the digits of an integer n:
# For example, reverse_int(12345) displays 54321.
def reverse_int(n):
reverse = 0
while(n > 0):
reminder = n %10
reverse = (reverse *10) + reminder
n = n //10
print("reverse o... |
30cc537fe2ab4847f8ed36ebe21c1e92e37d1abd | chlxry/cp2019 | /practical_2/q05_find_month_days.py | 930 | 4.28125 | 4 | # Write a program that prompts the user to enter the month and year, and displays the number of days in the month.
# For example, if the user entered month 2 and year 2000, the program should display that February 2000 has 29 days.
# If the user entered month 3 and year 2005, the program should display that March 200... |
59827c3b9924997ad3d6cf417a9224956d7e2db5 | kvmuralikrishna1993/ComputerNetworks | /m8/Assignment1/Socket_TCP_server.py | 2,051 | 3.765625 | 4 | # importing socket libraries
import socket
import sys
def value(string):
#Spliting Data.
data = string.split(" ")
if (data[4] == "Dollar"):
#required in dollars.
if(data[1] == "Yen"):
return int(data[2])/113.41
elif(data[1] == "INR"):
return int(data[2])/67
elif(data[1] == "Pounds"):
return int(da... |
9774d50167da1a14c5e022cd1c6f82edba10f0c4 | chches/hackathon03_reto1 | /main.py | 1,768 | 4.09375 | 4 | # RETO 1:
# Ingresar 5 notas de un alumno e imprimir lista de notas,
# nota promedio, nota menor, nota mayor.
# Considerar validaciones para las notas.
# 09:11
# Inicializando variables.
lista_notas = [] #Lista de notas.
cantidad_nota = 1 #Primera nota
no_es_nota = True #Booleano indicador numérico
nota = 0
p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.