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 |
|---|---|---|---|---|---|---|
f674ed8c87537ff6c77d1061c6a4114c5651f0b9 | johnadams2076/CozmoApps | /com/testlab/tensorflow/softmax.py | 418 | 3.53125 | 4 | # Solution is available in the other "solution.py" tab
import numpy as np
def softmax(x):
"""Compute softmax values for each sets of scores in x."""
# TODO: Compute and return softmax(x)
return np.divide(np.exp(x), np.sum(np.exp(x), axis=0))
# logits is a two-dimensional array
logits2 = np.array([
[1... |
7d7c95bd6a43fce8cfc87da2e4d8dc5273808109 | AnaBiaCosta/curso-python | /exercicios-python/28.py | 188 | 3.875 | 4 | import random
pc_num = random.randint(1,5)
user_num = int(input('Digite um número entre 1 e 5:'))
if pc_num == user_num:
print('Você ganhou!')
else:
print('Você perdeu...')
|
82f47a040300ce674aa595d9d55c3c6d8ce93f07 | AnaBiaCosta/curso-python | /exercicios-python/10.py | 124 | 3.671875 | 4 | dinheiro = int(input('Quantos reais você tem?'))
print('Após a conversão, você terá U${:.2f}!'.format(dinheiro/3.27)) |
0d524ec4827840823fa072ed07acf33acda04380 | AnaBiaCosta/curso-python | /aula9.py | 614 | 3.765625 | 4 | # frase = 'Curso em vídeo python'
# print(frase[::2])
# print(frase.count('í'))
# print(frase.upper().count('O'))
# nome = str(input('Nome:'))
# if nome == 'Bia':
# print('Você é muito linda!')
# print('Prazer em te conhecer {}!'.format(nome))
nome = str(input('Nome:'))
n1 = float(input('Nota 1:'))
n2 = floa... |
6414062cfb383ef209f7795d0bff929449db7bb6 | AnaBiaCosta/curso-python | /exercicios-python/29.py | 299 | 3.8125 | 4 | velocidade = int(input('Velocidade atual: '))
if velocidade <= 80:
print('Você está dentro da velocidade permitida')
else:
excesso = velocidade - 80
multa = excesso * 7
print('Você está {}km acima da velocidade permitida. Sua multa é de R${:.2f}'.format(excesso, multa))
|
990f49ff8b109750a5ea7e5c84e9a875ddae57f3 | AnaBiaCosta/curso-python | /exercicios-python/11.py | 245 | 3.84375 | 4 | altura = int(input('Altura da parede:'))
largura = int(input('Largura da parede:'))
area = altura * largura
tinta = area / 2
print('A área total é de {:.2f} metros quadrados \n Você precisará de {:.2f} litros de tinta'.format(area, tinta)) |
b13b91f5a1bd5637b5c354be3ac9970040dbfb9c | Abhi-BloodFeeD/Hacker-Rank-30-day-Python | /day10_binary/day19_binary.py | 529 | 3.71875 | 4 | array = []
def decimalToBinary(num):
if num > 1:
decimalToBinary(num // 2)
array.append(num % 2)
call = decimalToBinary(int(input()))
# print(array)
countOfOne = 0
maxCount = 0
for elements in array:
if elements == 1:
countOfOne += 1
if maxCount < countOfOne:
maxCoun... |
d9a7e68b60200c9a3e044c650eca0fae870f4879 | Biswajeet11/pythonscripts | /1.py | 96 | 3.828125 | 4 | def add(num1=6,num2=8):
res=num1+num2
print(res,end=' ')
print(num1)
add()
|
fc99640b6ee5a64ef1994f2f2d72eacc7c64e287 | morsedan/architecture_final | /Notes/day1.py | 1,986 | 3.734375 | 4 | import sys
# operation (op) codes
PRINT_JAKE = 1
HALT = 2
PRINT_NUM = 3
SAVE = 4
PRINT_REGISTER = 5
ADD = 6
print_jake_program = [
PRINT_JAKE,
PRINT_JAKE,
PRINT_JAKE,
PRINT_JAKE,
# HALT,
]
print_some_nums = [
PRINT_NUM,
10110010,
PRINT_NUM... |
1658511ddf06d9124b17445af3164864cdd45c39 | nilearn/nilearn | /examples/05_glm_second_level/plot_second_level_design_matrix.py | 1,994 | 4.34375 | 4 | """
Example of second level design matrix
=====================================
This example shows how a second-level design matrix is specified: assuming that
the data refer to a group of individuals, with one image per subject, the
design matrix typically holds the characteristics of each individual.
This is used i... |
ad6f8abb095b37bd8f2ca76a73b1e4a7a462d4ca | nilearn/nilearn | /examples/04_glm_first_level/plot_hrf.py | 5,159 | 3.953125 | 4 | """
Example of MRI response functions
=================================
Within this example we are going to plot the hemodynamic response function
(:term:`HRF`) model in :term:`SPM` together with the :term:`HRF` shape
proposed by G.Glover, as well as
their time and dispersion derivatives.
We also illustrate how users ... |
90fd4cb6fe30fa8f598a1f63845e0531989ea6c7 | nilearn/nilearn | /nilearn/glm/regression.py | 12,497 | 3.609375 | 4 | """Implement some standard regression models: OLS and WLS \
models, as well as an AR(p) regression model.
Models are specified with a design matrix and are fit using their
'fit' method.
Subclasses that have more complicated covariance matrices
should write over the 'whiten' method as the fit method
prewhitens the res... |
6aab57a97c53f874344ad65e3635988d9d929318 | wcass77/100daysofcode-with-python-course | /days/25-27-error-handling/dnd_game/program.py | 3,454 | 3.6875 | 4 | """
List of potential error states:
Invalid parameter for creature creation
The user enters something invalid: The program should recover, list options
The program should also respond correctly if you type out command
Keyboard interrupt: Program should exit gracefully
Life is less than 0: Should tell you that you're de... |
ee32b76c99c3f73551e82c2269d7e2a207003750 | opennlp/DeepPhrase | /commonutils/listutils.py | 795 | 3.546875 | 4 |
def get_unique_phrases(master_list, list_to_merge):
tokenized_master_list = []
unique_word_list = []
for original_phrase in master_list:
for word in original_phrase.split(" "):
tokenized_master_list.append(word)
for potential_merge_phrase in list_to_merge:
phrase_count = 0
... |
dc601ff5c2c3b835d582aefd734ce0bdf475dc30 | Pradeepnitw/tutorials | /leetcode/python/81.py | 1,293 | 3.53125 | 4 | class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if not nums:
return -1
pivot_idx = len(nums) - 1
for i, n in enumerate(nums):
if i != len(nums) - 1 and nums[i] ... |
5059b9893911260e61385eb3293cb0f6e2da9d19 | Pradeepnitw/tutorials | /cc150/1.1.py | 576 | 4 | 4 | import sys
"""
Implement an algorithm to determine if a string has all unique characters.
What if you cannot use additional data structures?
"""
def is_unique(s):
"""
sort character array in place to determine whether it have all
unique characters
"""
sorted_chars = sorted(s)
for i, c... |
e4ec3eb962d7c55450b9dbd0a2fdfe3cc989373a | loveAlakazam/leetcode | /104/MaximumDepthOfBinaryTree.py | 671 | 3.8125 | 4 | # https://leetcode.com/problems/maximum-depth-of-binary-tree/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if root is None: #루트가 가리... |
73800f48e0273cfc6a06cba88784c9f747b2d1ed | loveAlakazam/leetcode | /024/Swap_Nodes_in_pairs.py | 397 | 3.671875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def swapPairs(self, head: 'ListNode') -> 'ListNode':
if head==None or head.next==None:
return head
n= head.next
head.nex... |
22ce6cd5f1276831924a00b60d8465e6cf0945c7 | loveAlakazam/leetcode | /701/Insert_into_a_BST.py | 1,639 | 3.875 | 4 | #url: https://leetcode.com/problems/insert-into-a-binary-search-tree/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
... |
5d93ae106fca65d611a574a7ec216adc9bbfb185 | ronaldsnyder/Learn-Python-The-Hard-Way | /chapter36/my36.py | 2,863 | 3.828125 | 4 | #Name: my36.py
#Date: 1/15/2014
#Author: Ron Snyder
#Purpose: Project for the first 36 chapters of LPTHW
from sys import exit
import random
def fight():
life = random.randint(1,10)
return life
def start():
print """
You enter the underground dungeon and find a room
to your right, left and ... |
25702a05b5ecc7944d3f228cfde114303a50ef88 | truerandom/simpletree | /nodo.py | 1,140 | 3.921875 | 4 | class nodo(object):
def __init__(self,data=None,parent=None):
#print 'node init %s' % data
self.data = data
self.children = []
self.parent = parent
if self.parent is not None: self.level = parent.level+1
else: self.level = 0
if parent is not None: parent.addChildren(self)
def getChildren(self): return ... |
762fe58600c4602859e746c71b4bb1a0639b0c6b | xzguy/LeetCode | /Problem 101 - 200/P145.py | 1,279 | 3.890625 | 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:
# recursive
def postorderTraversal(self, root: TreeNode) -> [int]:
traversal = []
def sub(root: ... |
cf1c9bc02965e2b2a41da8c63e9c0539aeed1970 | xzguy/LeetCode | /Problem 101 - 200/P105.py | 1,330 | 3.515625 | 4 | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def buildTree(self, preorder: [int], inorder: [int]) -> TreeNode:
if not preorder:
return None
root_val = preorder[0]
... |
fa7f7830eec3f0c6ea1d8aa88b558a7359011210 | xzguy/LeetCode | /Problem 1001 - 1100/P1019.py | 1,112 | 3.8125 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def nextLargerNodes(self, head: ListNode) -> [int]:
nums = []
while head:
nums.append(head.val)
head = head.next
... |
a952a899ce253601dbad4ffdb5cf3bf2ef8b0682 | xzguy/LeetCode | /Problem 1 - 100/P44.py | 1,142 | 4.03125 | 4 | '''
Analysis:
The key point in this problem is '*'. For some string and
pattern, there may be multiple ways for matching. When there
is a '*', we iterate all possibilities of star covering by
indicate the last star match.
'''
def isMatch_iterate(s: str, p: str) -> bool:
s_ptr = 0
p_ptr = 0
star_index = ... |
d3893d8b61ad44a4cce0491d798e1869b1a76443 | xzguy/LeetCode | /Problem 1001 - 1100/P1034.py | 1,447 | 3.515625 | 4 | class Solution:
def colorBorder(self, grid: [[int]], r0: int, c0: int, color: int) -> [[int]]:
if not grid:
return grid
row = len(grid)
col = len(grid[0])
target_color = grid[r0][c0]
stack = [(r0, c0)]
# coloring the area with -1
while stack:
... |
102262d1ba6f6510738711b16360d05010ec68b2 | xzguy/LeetCode | /Problem 1 - 100/P15.py | 603 | 3.515625 | 4 | import collections
def threeSum(nums: [int]) -> [[int]]:
if len(nums) < 3: return []
counter = collections.Counter(nums)
tri = [[0,0,0]] if counter[0] > 2 else []
negative = [x for x in counter if x < 0]
positive = [x for x in counter if x >= 0]
for n in negative:
for p in positive:
... |
f872fdef1cc3717b4a0147129246bd44e96b7143 | xzguy/LeetCode | /Problem 1 - 100/P74.py | 767 | 3.546875 | 4 | class Solution:
def searchMatrix(self, matrix: [[int]], target: int) -> bool:
if not matrix or not matrix[0]: return False
row = len(matrix)
col = len(matrix[0])
l, r = 0, row * col - 1
while (l != r):
mid = (l + r - 1) // 2
if target <= matrix[mid //... |
ddbc3888cb978e232828c1031c82fed784e84a09 | xzguy/LeetCode | /Problem 101 - 200/P172.py | 402 | 3.78125 | 4 | class Solution:
# only a pair of factor 2 and 5 can contribute
# to trailing zeros. In factorial, 2 is much
# more than 5. So we only need to consider 5.
def trailingZeroes(self, n: int) -> int:
res = 0
factor_5 = 5
while factor_5 <= n:
res += n // factor_5
... |
043c0517264ea8076bc5775c2f583ca44643d7e1 | xzguy/LeetCode | /Problem 201 - 300/P242.py | 371 | 3.78125 | 4 | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
t_set = set(t)
s_set = set(s)
if s_set != t_set:
return False
for i in t_set:
if i not in s or s.count(i) != t.count(i):
return False
return True
s = "anagram"
t = "n... |
13968d3fd8bc7a308ed7cb6d0ab1c0eca5787845 | xzguy/LeetCode | /Problem 101 - 200/P124.py | 2,275 | 3.546875 | 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 maxPathSum(self, root: TreeNode) -> int:
left_max = right_max = through_root = float('-inf')
if r... |
26104d077e0997eb8bf4d100cb57efd586372498 | xzguy/LeetCode | /Problem 101 - 200/P106.py | 1,333 | 3.609375 | 4 | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def buildTree(self, inorder: [int], postorder: [int]) -> TreeNode:
if not inorder:
return None
root_val = postorder[-1]
... |
452213bcd0b33f9bb937e32a5d6e0b0c573427cf | xzguy/LeetCode | /Problem 1 - 100/P84.py | 3,258 | 3.5 | 4 | class Solution:
def largestRectangleArea_bf1(self, heights: [int]) -> int:
if not heights:
return 0
max_area = heights[0]
for l in range(len(heights)):
for r in range(l, len(heights)):
area = (r - l + 1) * min(heights[l: r + 1])
if area... |
5d62e1278152a6d65c4f84f4d6cf22c1937704b8 | xzguy/LeetCode | /Problem 201 - 300/P274.py | 1,072 | 3.5 | 4 | import heapq
class Solution:
def hIndex(self, citations: [int]) -> int:
citations.sort()
N = len(citations)
i = N-1
while i >= 0:
if citations[i] >= N-i:
i -= 1
else:
break
return N-1-i
# binary search
def hInd... |
fa8ea328cf97541729f03527c553a64c19a7f9c7 | xzguy/LeetCode | /Problem 101 - 200/P146.py | 3,792 | 3.78125 | 4 | import collections
'''
The key point in this problem is to efficiently remove
an item from / add an item on one end / pop an item from
the other end, from a container.
Double linked list has this property: constant time remove
a node and add or pop a node from either end.
'''
# native class implementation
class LRUCach... |
deca0e840709e4b2106fcbced8177416f6914821 | xzguy/LeetCode | /Problem 1 - 100/P56.py | 415 | 3.859375 | 4 | def merge(intervals: [[int]]) -> [[int]]:
# sort the intervals by its first value
intervals.sort(key = lambda x: x[0])
merged = []
for interval in intervals:
if not merged or merged[-1][1] < interval[0]:
merged.append(interval)
else:
merged[-1][1] = max(interval[... |
5405357f599beb6d37451cc5bf14754c83b7c6f3 | MLWhiz/HackerRank | /Gemstones.py | 321 | 3.625 | 4 | num1 = input()
dict1={}
for i in range(0,num1):
stri= str(raw_input())
stri1=list(set([a for a in stri]))
for elem in stri1:
if elem in dict1:
dict1[elem]+=1
else:
dict1[elem]=1
num=0
for key in dict1:
if dict1[key]==num1:
num+=1
print nu... |
1f491e7ff4ab6cd6f6425f80af8f6319ce6fca07 | MLWhiz/HackerRank | /ConnectingTowns.py | 406 | 3.5625 | 4 | #https://www.hackerrank.com/challenges/connecting-towns/submissions/code/10588544
# Enter your code here. Read input from STDIN. Print output to STDOUT
# Enter your code here. Read input from STDIN. Print output to STDOUT
ts= input()
for i in range(0,ts):
n=input()
tlist=[int(x) for x in raw_input().split... |
10ef6d10e1695fbfb8440bb554f8fe41a6295d29 | MLWhiz/HackerRank | /MultipleLinearRegressionPredictingHousePrices.py | 756 | 3.53125 | 4 |
#https://www.hackerrank.com/challenges/predicting-house-prices/submissions/code/10573205
import numpy as np
from sklearn import linear_model
data =str(raw_input())
m, n=data.split(" ")
m=int(m)
n=int(n)
X=[]
Y=[]
for i in range(0,n):
data2 = str(raw_input()).split(" ")
data = [float(x) for x in d... |
7af08fa5b05de378ec4ece1c7dfc29824d1cab59 | jing341/pythonWeb-scraper | /main.py | 274 | 3.953125 | 4 | tuples = ("test", "tuple", 123423.234, 134, True, False, None)
print(tuples)
print(tuples[1])
python = {
"name": "python",
"age": 100,
"korean": False
}
print(python)
print(python["age"])
python["year"] = 1243
print(python)
print(tuples[0:3]) |
842cad998f87cf3b11fd5f258970ddd7c5a149b3 | hectorplinio/Python | /primos prueba.py | 640 | 3.671875 | 4 | #3.- Escribe un programa que pida un número entero y diga si es primo, y de no serlo que lo descomponga en factores
x= int(input("Escriba un número pasa saber si es primo: "))
z=1
contador=0
lista_p = [2]
lista_n = []
lista_f = []
y=1
for i in range (x):
if x %z==0:
contador+=1
lista_n.append(z)
... |
3982ef9b1b5582660b0333b37e751d62571b9c2a | hectorplinio/Python | /EJERCICIO2POO.PY | 364 | 3.515625 | 4 | class Persona:
def __init__(self, nombre, edad):
self.nombre=nombre
self.edad=edad
def imprimir (self):
print (self.nombre)
def mayor (self):
if self.edad >= 18:
print ("Es mayor de edad.")
else:
print ("No es mayor de edad.")
p1=Per... |
a19ab2d3920ca3f956ca83719af3124ff6b9b073 | lberge17/learning_python | /strings.py | 368 | 4.5 | 4 | my_string = "Hello world! I'm learning Python."
print("Hello")
print(my_string)
# using square brackets to access a range of characters
print(my_string[26:30]) # prints "Pyth"
# using commas to print two items
print("My message is:", my_string[13:33]) # prints "My message is: I'm learning Python."
# using string in... |
72196614c8ca5e76dbd1716456327591bf7c03c9 | ezenico/git-demo | /prueba.py | 184 | 3.953125 | 4 | print("Hola mundo")
# Basic function adition
x = int(input("Please enter the first number: "))
y = int(input("Please enter the second numeber: "))
print("The adition result is: ", x+y) |
cf4a27169e28eecdcdcef70b4d5e500f5465e165 | EnoqueReuel/pythonexercicios | /ex010.py | 175 | 3.9375 | 4 | m = float(input('uma distância em metros:'))
print('a medida de{} corresponde a \n{}km \n{}hm \n{}dm \n{}cm \n{}mm'.format(m,(m/1000),(m/100),(m/10),(m*10),(m*100),(m*1000))) |
baff4b4109f9c21948ba543f372fda507def8c30 | dylanhoover/SCU-Coursework | /COEN140/lab1/class3.py | 310 | 3.6875 | 4 | class Person:
def __init__(self, name, jobs, age=None):
self.name = name
self.jobs = jobs
self.age = age
def info(self):
return(self.name, self.jobs)
rec1 = Person('Bob', ['dev','mgr'],40.5)
rec2 = Person('Sue', ['dev','cto'])
print(rec1.jobs)
print(rec2.info())
|
67fdf8aa195344374abaaf6ffa54b07e8a4878e6 | drummyfish/rpg | /src/tools.py | 2,232 | 3.578125 | 4 | ## \file general.py
# this file contains functions and classes for helper tools for the
# game
import pygame
## Makes an map string from given bitmap image.
#
# @param image_surface image (Surface) from which to make the map
# @param color_map say how to interpret the colors in the image, this
# should be... |
38df52b41ddfa11375af811b2bf28f7bd1656e3f | haideraheem/Simple-Python-Programs | /Divisible by 7 but not by 5.py | 807 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 15 05:38:13 2018
@author: Haider Raheem
"""
valid= True
x= int(input("Enter lower bound: "))
y= int(input("Enter upper bound: "))
c = 0
c2 = 0
total =0
if y < x:
print("Invalid range")
valid=False
else:
for i in range(x, y+1, 1 ):
... |
a495670c32c7f8018ea669e90240ab782162fbaf | haideraheem/Simple-Python-Programs | /question 3 lab 2.py | 519 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""9
Created on Mon Oct 15 08:42:49 2018
@author: Haider Raheem
"""
x = 0
while x == 1 or x == 0:
x = int(input("Enter an integer (except 0 and 1): "))
x =x**30
j = 0
i = 0
count = 0
for i in range(-x,x) or range(x, -x):
for j in range(2,9):
if i ** j == x... |
f2e5fd70b494d9e1e30b79028e83f1f65b3bfaf9 | dimagapey/Lesson_13.py | /Lesson_13.py | 849 | 3.8125 | 4 | from random import randint
class Street:
def __init__(self, number):
self.number = number
self.houses = []
for i in range(1, randint(5, 20)):
self.houses.append(House(i))
class House:
def __init__(self, number):
self.population = randint(1, 100)
self.numbe... |
ec39e9b0fffa050ae20a40a3a73bb23cbc5f606b | manisha-jaiswal/Division-of-apples | /problem19.py | 1,258 | 4.25 | 4 | """
-------------------------------------Problem Statement:--------------------------
Harry potter has got n number of apples. Harry has some students among whom, he wants to distribute the apples. These n number of apples are provided to harry by his friends and he can request for few more or few less apples.
You... |
a08e8e93e1c8dc5c92f95ef326670a56de3e82bf | programjames/timpviewcsclubweek3 | /mymap.py | 2,438 | 3.828125 | 4 | """
Make a map.
"""
class Map():
def __init__(self):
self.map = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0,... |
4e761b95dd4acdc75bb0bc0f38fb85588bc7e135 | ClestinaK/chem160module7 | /strings.py | 428 | 3.90625 | 4 | str1 = "Hello world"
print(str1)
str2 = '1 2 3 4 5 6' #Using alternate quotes
print(str2)
str4 = str1 + str2 #Adding strings
print(str4)
greetings = 4*"Hi " #Multiplying strings
print(greetings)
str5 = "When in the course of human events"
print(len(str5))
print(str5[0])
print(str5[24:])
print(str5[5:17])
s1 = "alpha"
... |
9aba0f6bbb720a5c11661a6a3fa0bd33d9e53151 | snehaks/powerball | /powerball.py | 4,638 | 3.75 | 4 | import sys
def Validate(x, userNums):
if (x not in userNums) and (1 <= x <= 69) and type(x) == type(1):
return True
else:
return False
def main():
fname = input("Enter your first name: ")
lname = input("Enter your last name: ")
userNums = []
try:
error= 'Error: Input entered must be a number from 1 thru 6... |
296fb4507878591bdde602c63284b9785971509d | hungd25/projects | /CS6390/HW2_P3.py | 2,213 | 4.59375 | 5 | """
"""
def get_input():
"""
# Get height and weight from the user and validate. If inputs are (negative numbers or strings),
the program should throw an error message.
: return: height, weight
"""
try:
# get user input and convert to type float
height_input = float(input("E... |
cadd60c863a56392e0e0fb230241f14c4370e454 | sivakumar-raju/siva | /nearesteven.py | 60 | 3.734375 | 4 | hi=int(input())
if hi%2==0:
print(hi)
else:
print(hi-1)
|
b9e447883c8f9e2d1ec6c5d69082990566f9f363 | sivakumar-raju/siva | /primeornot.py | 179 | 3.515625 | 4 | n=int(input())
a=2
k=1
while(a<n):
if(n%a==0):
k=0
break
else:
a=a+1
if k==0:
print('no')
else:
print('yes')
|
c45237cb94edc287534e0e360a78ea8802d4bd21 | KuboBahyl/coding-interviews | /Algo topics/Problems Medium/FindConsSum.py | 536 | 3.859375 | 4 | # Find count subarr of given sum
arr = [1, 4, 20, 3, 10, 5]
summ = 33
def find_count_sum(arr, summ):
start = end = 0
queue_sum = arr[0]
while end < len(arr):
if queue_sum == summ:
return arr[start:end + 1]
if queue_sum < summ:
end += 1
if end == len(ar... |
85f78230647563d82df5d12c0b64aea23bf795c2 | KuboBahyl/coding-interviews | /Algo topics/Reconstructions/Graph.py | 2,230 | 3.84375 | 4 | # unidirectional graph
class Graph(object):
def __init__(self):
self.vertices = {}
def addEdge(self, fromVertex, toVertex):
# check if vertex is already present
if fromVertex in self.vertices:
self.vertices[fromVertex].append(toVertex)
else:
self.vertices... |
7400e0137e19c5c9e2a1c84464812465904be178 | KuboBahyl/coding-interviews | /Algo topics/Problems Advanced/CreateCombinations.py | 1,222 | 3.8125 | 4 | # Create combinations from given string
# In: "a{bb,c}dd{e,fff}"
# Out: "abbdde", "abbddfff", "acdde", "acddfff"
def print_combinations(string):
N = len(string)
big_arr = []
in_bucket = False
temp_arr = []
temp_bucket = ''
i = 0
while i < N:
character = string[i]
if characte... |
123e2d2fac7920c6318c2b1df5392f9238814525 | KuboBahyl/coding-interviews | /Algo topics/Problems Simple/StringReverse.py | 208 | 4 | 4 | # Reverse string in-place
def reverse_string(string: str):
N = len(string)
for i in range(N):
string = string[:i] + string[-1] + string[i:N - 1]
return string
reverse_string('abcdefgh') |
bfb1d92ddaba35f2bc9432632d6ec24610cce767 | KuboBahyl/coding-interviews | /Algo topics/Problems Simple/ArrayRotation.py | 300 | 4 | 4 | # Array - rotation
def rotate_array(arr, shift):
def rotate_once(arr):
for i in range(len(arr) - 1, 0, -1):
arr[i], arr[i - 1] = arr[i - 1], arr[i]
return arr
for i in range(shift):
rotate_once(arr)
return arr
rotate_array([0, 1, 2, 3, 4, 5, 6], 3) |
ee170154caea640804d6faa0ff0a151b88894de4 | KuboBahyl/coding-interviews | /Algo topics/Problems Medium/JoinIntervals.py | 719 | 4 | 4 | # Overlapping intervals - given various intervals, return the overlapped areas
# prop: it's sorted on starting intervals
intervals = [[1, 3], [2, 4], [5, 7], [6, 8], [9, 15], [10, 12], [13, 14], [9, 15]]
# out: [1,4], [5,8], [9,15]
def merge_all(intervals):
if len(intervals) == 0:
return []
merged_a... |
5299aa0610a062f7e713de93c6d16b7297eba07f | KuboBahyl/coding-interviews | /Algo topics/Reconstructions/selection_sort.py | 354 | 3.84375 | 4 | # SELECTION SORT
# search for minimum and swap it to the front of stack
# O(n^2)
def selection_sort(arr):
def swap(i, j):
arr[i], arr[j] = arr[j], arr[i]
n = len(arr)
for i in range(n):
pos = i
for j in range(pos + 1, n):
if arr[j] < arr[pos]:
pos = j
... |
1e2d4994b38eb03e39ddf3c95b506f81754f13dc | salimsuprayogi/program_hitung_berat_badan | /program_pertama/cara_pertama/main_broca_woman.py | 659 | 3.921875 | 4 | # Mentor = Muhammad Nasrullah
# Author = Salim Suprayogi
print("=======================================================")
print("Hitung berat badan ideal wanita berdasarkan rumus broca")
print("=======================================================")
tb = input("Berapa tinggi badan kamu :")
print("=================... |
af0e869283f208a8dade1f93c7e5432080a4cb19 | naadzya/labs_python | /lab_2/task_5_tojson.py | 3,750 | 4 | 4 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
from math import modf
import argparse
__all__ = ['to_json']
def read_from_file(filename: str):
with open(filename) as f:
line = f.readline()
return eval(line)
def int_to_json(obj: int):
"""Serialize int object to a JSON formatted str
"""
js... |
0a9995429e4b4f602b43af0bce4c8bebfc1a708b | michaelandric/insight_stuff | /data_challenge/coding_challenge/kutchko_coding_challenge/listSorting.py | 1,504 | 3.671875 | 4 | #!/usr/bin/env python3
import sys
import re
# remove extra characters and classify into word/integer
def process(item):
if re.search('[A-Za-z]', item): # is a word
newString = re.sub('[^A-Za-z]', '', item)
return ('string', newString)
else: # is a number
newNumber = int(re.sub('[^0... |
c94d347519c2f7c07c09c516731a572aa3fc5fe5 | babiswas2020/Design-Pattern | /Prototype.py | 705 | 3.734375 | 4 | import copy
class Prototype:
def __init__(self):
self.objects={}
def register_object(self,name,obj):
self.objects[name]=obj
def unregister_object(self,name):
del self.objects[name]
def clone(self,name,**attr):
obj=copy.deepcopy(self.objects.get(name))
obj.__dict__.update(... |
fbe0156cf816919f776e2f7e68c70418a64385d4 | babiswas2020/Design-Pattern | /factory4.py | 662 | 3.96875 | 4 | class Dog:
def speak(self):
return "Woof"
def __str__(self):
return "Doggy"
class Dog_Factory:
def get_pet(self):
return Dog()
def get_food(self):
return "Meat"
class Pet_Factory:
def __init__(self,pet_factory):
self.pet_factory=pet_factory
def show_pet... |
05e58c396dd58b558cb6fcf143006868843b61d3 | tyagi619/Machine-Learning | /Polynomial_Regression/polynomial_regression.py | 1,336 | 3.5625 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#get train data
data = pd.read_csv('xy.csv')
#analyse the data
print(data.head())
# print(data.describe())
# plt.scatter(data['x'],data['y'])
# plt.show()
#add x square column
data['x_2'] = [x**2 for x in data['x']]
x = np.array(data.drop('y',axis... |
c3a577bd7eebbae46060cbf729dd5a35078aef70 | halysl/python_module_study_code | /src/study_cookbook/8类与对象/调用父类方法.py | 663 | 3.828125 | 4 | # -*- coding: utf-8 -*-
# 在子类中调用父类的某个已经被覆盖的方法
# super 的使用相对比较复杂,会更新一篇文章说这个
class A(object):
def __init__(self):
self.x = 0
def spam(self):
print('A.spam')
class B(A):
def __init__(self):
super().__init__()
self.y = 1
def spam(self):
print('B.spam')
s... |
22683aaee47a88d533104f9c2c70fe0eae76a758 | halysl/python_module_study_code | /src/study_cookbook/3数字日期和时间/矩阵与线性代数运算.py | 266 | 3.671875 | 4 | # -*- coding: utf-8 -*-
import numpy as np
from numpy import linalg
def create_matrix():
m = np.matrix([[1, -2, 3], [0, 4, 5], [7, 8, -9]])
print("m={}\nm.T={}\nm.I={}\n".format(m, m.T, m.I))
print("")
if __name__ == "__main__":
create_matrix()
|
ae518f0c07c097f9c9d190a54208d4de7569fcd6 | halysl/python_module_study_code | /src/study_cookbook/5文件与IO/创建临时文件和文件夹.py | 648 | 3.828125 | 4 | # -*- coding: utf-8-*-
from tempfile import TemporaryFile, NamedTemporaryFile
def example_create_temp_file():
# 创建匿名文件
with TemporaryFile("w+t") as f:
print("filename:{}".format(f.name))
f.write("Hello World\n")
f.seek(0)
data = f.read()
print(data)
def example_crea... |
766e656edabc297cb13cb1a60c48193c5ef00e43 | halysl/python_module_study_code | /src/study_cookbook/3数字日期和时间/计算当前月份的第一天和最后一天.py | 753 | 3.984375 | 4 | # -*- coding: utf-8 -*-
from datetime import datetime, date, timedelta
import calendar
def get_month_range(start_date=None):
# 先 生成一个date对象
if not start_date:
start_date = date.today().replace(day=1)
else:
start_date.replace(day=1)
# 通过calendar.monthrange()确定当前日期所在的月份有多少星期和多少天
wee... |
e24ded18c2bb0b69e89b955d90e9f658d644e5ec | halysl/python_module_study_code | /src/study_cookbook/1数据结构和算法/对可hash对象进行数量统计.py | 1,186 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
#=============================================================================
# FileName:
# Desc: 通过Counter类对可hash对象进行数量统计
# Author: 刘志
# Email: halysl0817@gmail.com
# HomePage: ${link}
# Version: 0.0.1
# LastChange: 2018-11-28 15:24
# History:
# slogan: 狂风骤雨催纸伞,游人浪迹步不... |
12ef4d02bc8801b3678d9d3125c0366b5a5c4a6c | halysl/python_module_study_code | /src/study_ctf/zhalan_object.py | 1,071 | 3.65625 | 4 | class Get_Data(object):
def __init__(self):
pass
def get_string(self):
string = input("请输入栅栏加密的文字:")
return string
def get_code(self):
code = input("请输入分栏:(0代表从2到6逐个分栏):")
code = int(code)
return code
class zhalan(object):
def __init__(self):
pass... |
9e3eb56a36bb869ae86c24673b20e0f697381071 | halysl/python_module_study_code | /src/study_ctf/ROT13.py | 928 | 3.8125 | 4 | import re
def ree():
isnum = re.compile(r'\d')
isalpha_am = re.compile(r'[a-m]')
isalpha_nz = re.compile(r'[n-z]')
return isnum,isalpha_am,isalpha_nz
def get_data():
string = input("请输入经过ROT13加密的字符串:")
string = string.lower()
return string
def ROT13(string):
string_temp = []
isnum... |
e4ab6a0cc12981086a7ad4675949479da48a4fe1 | halysl/python_module_study_code | /src/study_cookbook/2字符串和文本/字符串对齐.py | 689 | 4 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def simple_format():
# 简单的字符串对齐,直接使用 ljust、rjsut 或者 center 即可。
text = "Hello World"
print(text.ljust(20))
print(text.ljust(20, "*"))
print(text.rjust(20))
print(text.rjust(20, "*"))
print(text.center(20))
print(text.center(20, "*"))
def c... |
497a07b784d74cbfdb58ac5cf34f200ea90e2512 | halysl/python_module_study_code | /src/study_checkio/Three Words.py | 359 | 3.6875 | 4 | import re
def three_word(text):
a = re.sub(r'[^a-zA-Z]',"?",text)
print(a)
a = a.split("?")
b = 0
for i in a:
try:
if(i[0].isalpha()):
b = b*10+1
except:
b = b*10
b = str(b)
string = "Hello World hello"
text = "He is 123 man... |
d4a8e2b76d5cce35ebceb4df5064a07886a2d14f | halysl/python_module_study_code | /src/study_checkio/Fizz buzz.py | 768 | 4.5 | 4 | '''
https://py.checkio.org/mission/fizz-buzz/
"Fizz buzz" is a word game we will use to teach the robots about division. Let's learn computers.
You should write a function that will receive a positive integer and return:
"Fizz Buzz" if the number is divisible by 3 and by 5;
"Fizz" if the number is divisible by... |
12ab232125ed90cbb8c19aa08924a027f36a3146 | halysl/python_module_study_code | /src/study_checkio/Second Index.py | 1,015 | 4.28125 | 4 | '''
https://py.checkio.org/mission/second-index/
You are given two strings and you have to find an index of the second occurrence of the second string in the first one.
Let's go through the first example where you need to find the second occurrence of "s" in a word "sims". It’s easy to find its first occurrence ... |
4b820ea2ddff09244bfb9a7b6acdfff0e7e5a152 | Edgarchuk/2pixelgame | /main.py | 5,542 | 3.515625 | 4 | import random
class pointmap:
def __init__(self,type,hp = 255):
self.type = type
self.hp = hp
class map:
def __init__(self,w,h):
self.wpoint = w
self.hpoint = h
self.w = w * 2 + 1
self.h = h * 2 + 1
self.maplab = [[0 for q in range(self.h)] for i in rang... |
26574308c84e26256aab26abae95b62c2f9142a3 | josephj02233/joseph0426 | /pylesson9/lab9(2).py | 126 | 3.859375 | 4 | mylist = ["joseph","ben","hanna","nicole","lala"]
def first(mylist):
for i in mylist:
print(i[0])
first(mylist)
|
054f7f9fdfeb109480adf03d997adb5f0b60c9ad | josephj02233/joseph0426 | /pylesson11/11.2ex2.py | 1,203 | 3.671875 | 4 | import random
class inventory:
def __init__(self, m, n, c="", p=""):
self.manufacture = m
self.name = n
self.catagory = c
self.UPC = random.randint(0, 1000000000)
self.price = p
def serhes(self, newm, newn, newc):
self.manufacture = newm
self.name = newn
... |
01a20da0d0a7e077548c95ec0e76828d9b28746d | KentFujii/doing_math | /chapter5/lessons/roll_a_dice.py | 335 | 3.828125 | 4 | import matplotlib.pyplot as plt
import random
target_score = 20
def roll():
return random.randint(1, 6)
score = 0
num_rolls = 0
while score < target_score:
die_roll = roll()
num_rolls += 1
print('Rolled: {0}'.format(die_roll))
score += die_roll
print('Score of {0} reached in {1} rolls'.format(scor... |
1c65c8a6141a2fcc8233f39af36e86749b02cdcb | KentFujii/doing_math | /chapter7/lessons/derivative_calculator.py | 396 | 3.6875 | 4 | from sympy import Symbol, Derivative, sympify, pprint
from sympy.core.sympify import SympifyError
def derivative(f, var):
var = Symbol(var)
d = Derivative(f, var).doit()
pprint(d)
f = input('Enter a function: ')
var = input('Enter the variable to differentiate with respect to: ')
try:
f = sympify(f)
e... |
59f6f884f6b7bd178db4c9b73594204feacda533 | KentFujii/doing_math | /chapter1/lessons/fraction.py | 76 | 3.75 | 4 | from fractions import Fraction
print(Fraction(input('Enter a fraction: ')))
|
47d0464a02a778306eb170b12bd379fdfee93af4 | gramanicu/labASC | /lab02/task2.py | 1,164 | 4.25 | 4 | """
Basic thread handling exercise:
Use the Thread class to create and run more than 10 threads which print their name and a random
number they receive as argument. The number of threads must be received from the command line.
e.g. Hello, I'm Thread-96 and I received the number 42
"""
from random imp... |
aabe2f07b42986e8118c0ad4a3c074d6e2813308 | flyingaura/PythonLearning | /PY.exercise/exer0216002.py | 1,038 | 3.71875 | 4 | #! /usr/local/bin/python3
# -*- coding: utf-8 -*-
import threading, time
class MyThread(threading.Thread):
def __init__(self, ThreadID, ThreadName, delay, counter=5):
threading.Thread.__init__(self)
self.ThreadID = ThreadID
self.ThreadName = ThreadName
self.delay = delay
se... |
e091f71a69ad6ef212517a82cc3b40b530fc81dc | flyingaura/PythonLearning | /LearnOOP/learning0321002.py | 889 | 3.984375 | 4 | # -*-coding: utf-8 -*-
# 学习海龟绘图
import turtle
# 定义一个画N角星的函数
def DrawStar(n,step = 100): #n为星形图的顶点数,step为星形边长
if(not isinstance(n,int)):
raise ValueError('The type of star_top_number is Wrong! ')
# if(not isinstance(degree,(int,float))):
# raise ValueError('The type of star_top_degree is Wrong... |
58958ca1378f1cedc0cca02cedfc127e36da7ea1 | flyingaura/PythonLearning | /LearnOOP/learning0419001.py | 1,154 | 3.71875 | 4 | # -*- coding: utf-8 -*-
from LearnModule import StringSplit
from LearnModule import MY_math
import math
# from LearnModule import String_func
#
# origin_str = 'when you are thinking how to spend several hard-won lepta, when you are wondering whether new money'
# print(String_func.MY_replace(origin_str,'are','<-->',1))... |
9a3238fa2a37850c15df278017457807432cde9c | flyingaura/PythonLearning | /PY.exercise/exer0905001.py | 1,873 | 4.1875 | 4 | """
定义一个有理数的类,并实现有理数据的加减乘除运算 Rational(N1,N2)
"""
from LearnModule import MY_math
class Rational(object):
def __init__(self,N1,N2 = 1):
if(not isinstance(N1,int) or not isinstance(N2,int)):
raise ValueError('有理数的分子和分母都必须为整数!')
if(N2 == 0):
raise ZeroDivisionError('分母不能为零!')
... |
187a16f3033b0ac6749dd2b9f1279feccc5e479b | flyingaura/PythonLearning | /LearnOOP/learning0411001.py | 1,541 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
=========== 做作业 ==========
chapter 3.6
exercise 2 帕斯卡三角形
"""
from LearnModule import MY_math
# for i in range(10,100):
# for j in range(100,1000):
# if(MY_math.if_synnum(i) and MY_math.if_synnum(j)):
# if(MY_math.if_synnum(i + j) and (i + j) >= 1000):
# ... |
11dfcfb43b8e3136ba24e73e6c0d67d4df25c3ca | flyingaura/PythonLearning | /PY.exercise/exer0901002.py | 3,130 | 4 | 4 | # -*- coding: utf-8 -*-
import math
import random
class Point(object): #定义一个经纬度坐标类
def __init__(self,x = 0.0,y = 0.0):
self.x = x
self.y = y
def GetPoint(self):
return (self.x,self.y)
def Distance(self,Pinstance):
return math.sqrt((self.x - Pinstance.x) **2 + (self.y - P... |
9090a64fc57ebed7d35c267b5512d114efa0df59 | flyingaura/PythonLearning | /PY.exercise/exer1023001.py | 2,608 | 3.765625 | 4 | # -*- coding: utf-8 -*-
import csv,random
class goods(object): #定义一个商品的类,做为帐单的基类
def __init__(self,goodsID,goodsname,goodsprice,goodsdecr):
self.goodsID = goodsID # goodsID做为主键
self.goodsname = goodsname
self.goodsprice = goodsprice
self.goodsdecr = goodsdecr
def __str__(... |
5b0fb3ca5e58e8cdccde250132218be945a7e589 | flyingaura/PythonLearning | /LearnOOP/learning0214002.py | 1,202 | 3.84375 | 4 | # 学习类和实例的用法(5)
# -*- coding: utf-8 -*-
class screen(object):
@property
def width(self):
return self._width
@property
def height(self):
return self._height
@width.setter
def width(self,value):
if (not isinstance(value,int)):
raise ValueError('the type of wi... |
c94b1dee471214dd9eb1d1e2e9e3afa821202bb4 | flyingaura/PythonLearning | /PY.exercise/exer0427002.py | 2,205 | 3.734375 | 4 | # -*- coding: utf-8 -*-
import os
# 定义一个检查文件是否存在的函数checkfile()
def checkfile(filepath):
file_Base = os.path.split(filepath)
if(file_Base[0] == ''):
file_dir = os.getcwd()
else:
file_dir = file_Base[0]
if(os.path.exists(file_dir)):
if(file_Base[1] in os.listdir(file_dir)):
... |
ae4db91301eb3f9195799a0f14192ececb40f029 | flyingaura/PythonLearning | /LearnOOP/learning0324001.py | 3,252 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
应用巴比伦算法计算一个整数的平方根
巴 比 伦 平 方 根 算 法 :
(a) 猜 测 数 字 的 平 方 根 。
(b) 用 猜 测 的 数 字 除 原 数 。
(c) 计 算 步 骤 (b) 的 商 与 猜 测 数 的 平 均 值 。
(d) 对 第 (c) 步 的 平 均 值 再 作 猜 测 。
(e) 如 果 新 的 猜 测 值 与 旧 的 猜 测 值 不 同 , 则 回 到 第 (b) 步 ; 否 则 , 停 止 。
"""
# 定义一个利用巴比伦算法计算整数平方根的函数
def Cal_Square(n,guess_m = None,tolerance = ... |
b410366231387b970aa7ac79b38e347d44c0d5f5 | flyingaura/PythonLearning | /LearnOOP/learning0330003.py | 1,604 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
=========== 做作业 ==========
chapter 3.6
question 56
"""
import math
from LearnModule import MY_math
import time
#定义一个判断该数是否为完全平方数的函数
def if_fullsquare(n):
try:
n = int(n)
except ValueError as e:
raise('参数错误:%s -->输入参数必须为正整数或能转换为正整数的字符串')
if(n <= 0):
return ... |
30175b05882049a2f17b6a799bb51914a9b08a89 | aizen-rish/design-patterns-course | /day13[15]/ex2.py | 901 | 3.578125 | 4 | """
"""
class MyIterator:
def __init__(self, c):
self.c = c
self.i = 0
def __next__(self):
if self.i < len(self.c.mylist):
self.i += 1
return self.c.mylist[self.i - 1]
else:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.