blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
709d16e136200a63293034a93874d66c775d7b15 | Sem31/Data_Science | /2_Numpy-practice/16_mathematical_functions.py | 661 | 3.9375 | 4 | # Mathematical Functions
import numpy as np #np is a alias name
#rounding function
#np.around(array,decimal)
print("Round function in numpy : ")
a = np.array([1.0,5.55,123,0.567,25.234])
print(a)
print('\nArray after rounding : ')
print(np.around(a))
print(np.around(a, decimals = 1))
print(np.around(a, decimals = -1... |
6d8131b97e888562562cd327fd41e049769c85b9 | JulesDesmet/lsh | /src/jaccard.py | 517 | 3.640625 | 4 | #!/usr/bin/env python3.9
from typing import TypeVar
Shingle = TypeVar("Shingle")
def jaccard(set_1: set[Shingle], set_2: set[Shingle]) -> float:
"""
Computes the Jaccard similarity between two sets.
:param set_1:
:param set_2: The sets for which the similarity should be computed.
:return: The... |
6410dd88b2218248e9fe437d25f6199b4c5add62 | Rathetsu/GoogleHashCode2021_DroneDelivery | /helpers.py | 816 | 3.625 | 4 | def is_order_complete(order,payload):
for item in order:
if item not in payload or payload[item] != order[item]:
return False
return True
def find_hq(warehouses,orders):
"""
Finds the closes warehouse to all orders such that drones cand drop products there
"""
min_war... |
db133eea811e2e8bb7834986d7d8160371c5c4af | lucas234/leetcode-checkio | /LeetCode/69.Sqrt(x).py | 732 | 3.71875 | 4 | # @Time : 2021/7/27 9:39
# @Author : lucas
# @File : 69.Sqrt(x).py
# @Project : locust demo
# @Software: PyCharm
def my_sqrt(x: int) -> int:
if x == 1: return 1
for i in range(int(x / 2) + 1):
if i * i == x:
return i
if i * i > x:
return i - 1
return i
prin... |
23e569b2e2832ed8b3f5832a741554303c6e68d7 | jalondono/holbertonschool-machine_learning | /supervised_learning/0x0D-RNNs/2-gru_cell.py | 1,952 | 3.5 | 4 | #!/usr/bin/env python3
"""GRU Cell """
import numpy as np
class GRUCell:
"""GRUCell class"""
def __init__(self, i, h, o):
"""
Constructor method
:param i: is the dimensionality of the data
:param h: is the dimensionality of the hidden state
:param o: is the dimensiona... |
5e3df1b73850a12efbd5b7ef01dd21b78598e71e | bionictruck/Game | /character.py | 1,463 | 3.921875 | 4 | def c_name():
while True:
try:
c_name = raw_input("Enter a name: ")
if len(c_name) > 2:
print "Hello " + c_name + ", prepare for your adventure." + "\n"
return c_name
else:
print "Sorry the name must contain at least 2 chara... |
7b16ff69cdb9ab97c90adf3eef25139a4859a108 | davidabcdef123/pythonDemo | /test1/src/main/ShuRuShuChu.py | 1,208 | 3.765625 | 4 | import math
hello = 'hello, runoob\n'
hellos = repr(hello)
print(hellos)
for x in range(1, 11):
print(repr(x).rjust(2), repr(x * x).rjust(3), end= '')
print(repr(x*x*x).rjust(4))
for x in range(1,11):
print('{0:0d}{1:3d}{2:4d}'.format(x,x*x,x*x*x))
print('l2'.zfill(5))
print('-3.14'.zfill(7))
print... |
a477083bccb434d507b3187b3b49a37a94c625ad | thileepanp/Python-practice | /string cleaning.py | 422 | 3.71875 | 4 | """
Functions to clean strings!!
"""
import re
def remove_punctuation(value):
return re.sub('[!@#$%^&*()"''<>?/,.~`{}[]\|]', '', value)
clean_ops = [str.strip, remove_punctuation,str.title]
result =[]
def clean_strings(strings, ops):
for value in strings:
for function in ops:
value = function(value)
re... |
dcf6bbbf0f75cfe99d7c75e1592df2a1b9c7a80e | AndrewCochran22/python-101 | /c_to_f.py | 272 | 4.21875 | 4 | # def celsius_to_fahrenheit(c):
# f = (c * 9/5) + 32
# return f
# celsius = float(input("Pick a celsius temp: "))
# print("Your temperature in fahrenheit is: ", celsius_to_fahrenheit(celsius))
number = int(input("Give me a Celsius degree: "))
F = (C * 9/5 + 32)
|
0c3b97e12b1b15ce1bb508790b7b8ebfb60d32df | qscf1234/pythontext | /day04/条件控制语句.py | 476 | 3.84375 | 4 | # -*-coding: utf-8 -*-
'''
if 语句
if-else语句
if-elif-else语句
格式:
if 表达式1:
语句1
elif 表达式2:
语句2
elif 表达式3:
语句3
。。。。。。。。。。。
else:
语句.......
'''
age = int(input())
if age < 0:
print('娘胎里')
elif age < 3 and age >= 0:
print('婴儿')
elif age < 6 and age >= 3:
print('童年')
elif age < 18 and age >= 6:
... |
74f8d0ffba6981b7aeb8d437a1fd6cdefe5f1f20 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2421/60605/241462.py | 215 | 3.703125 | 4 | def changeNum(string):
newstr = ""
for i in list(string):
if i == "9":
newstr = newstr + i
continue
newstr = newstr + "9"
break
print(input().strip()) |
a662a58f5e7d909f73d26fc5b3c375f7258e0f81 | saumya470/python_assignments | /.vscode/Abstraction/abstractionAssignment.py | 1,247 | 3.96875 | 4 | # Create an abstract parent class or interface - TouchScreenLaptop with two abstract methods - scroll() and click(). This complete
# abstract class should be inherited or extended by HP and DELL which are also abstract classes which implement the scroll() method.
# Then create two more classes- HPNotebook and DELLNoteb... |
be33ca14bf93746ed64854ad99788b41138db107 | barreto-jpedro/Python-course-exercises | /Mundo 02/Ex041.py | 487 | 4.15625 | 4 | print('Descubra em qual categoria você se encaixa!')
idade = int(input('Digite a sua idade: '))
if idade < 9:
print('Você será alocado na categoria MIRIM')
elif 9 <= idade and idade < 14:
print('Você será alocado na categoria INFANTIL')
elif 14 <= idade and idade < 19:
print('Você será alocado na catego... |
4f2d7e7d2766e30475afea7b7292850f084bad7b | lingxiao00/python_tutorials | /python小技巧/python interview/19 多线程创建常用方法.py | 1,451 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2019-01-23 22:27:22
# @Author : cdl (1217096231@qq.com)
# @Link : https://github.com/cdlwhm1217096231/python3_spider
# @Version : $Id$
import time
from threading import Thread
# 自定义线程函数
def my_threadfunc(name='python3'):
for i in range(2):
pr... |
a787ac1ba4671e29e9a031269a6235e05d20516e | Macielyoung/LeetCode | /152. Maximum Product Subarray/maxProduct.py | 604 | 3.5625 | 4 | #-*- coding: UTF-8 -*-
class Solution(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
cursor = nums[0]
num = len(nums)
imax = imin = cursor
for i in range(1, num):
if nums[i] < 0:
imax, imin =... |
bf13dfcbe61f9db8bbc0fff0008d89527c58e9de | Tanmay-Thanvi/DSA-and-Leetcode-Walkthroughs | /Dynamic Programming/max_len3_sub_array.py | 3,034 | 4.15625 | 4 | # Fixed size window
def max_sub_array(array, k):
running_sum = 0
maxValue = -2**31
# We iterate the entire length of the array
for i in range(len(array)):
# Build our running sum value with each iteration
running_sum += array[i]
# If i >= k-1 this means we have our wind... |
04c6dae4f347b4cea2059faf697be62e773cc518 | erjoalgo/pitchperception | /pitchperception/pitchperception.py | 4,692 | 3.578125 | 4 | #!/usr/bin/python
"""An interactive game to test the user's pitch perception abilities.
Inspired by "Measure your pitch perception abilities"
from http://jakemandell.com/adaptivepitch.
"""
import contextlib
import random
import subprocess
import time
import curses
try:
from ._version import __version__
except... |
6484b57595aaf3032c01377c40b3591903511f68 | asatiratnesh/Python_Assignment | /FileHandlingAssig/assig9.py | 360 | 3.84375 | 4 | # find out count of all the python files in any specific directory and subdirectory
import os
# Open a file
path = raw_input("Enter Dir Path: ")
count = 0
for root, dirList, fileList in os.walk(path):
for x in fileList:
if x.endswith(".py"):
count += 1
print "Count of python files in any specif... |
d28a036c02e504d9376f68cd65569ab32efa3b25 | Muscularbeaver301/WebdevelopmentSmartNinja201703 | /Homework/Homework_Boni/SecretNumberGameTryouts.py | 1,654 | 4 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#Libraries
import random
#variablen
secret = int(10 * random.random()) + 1
oldsecret = secret
guess = 0
#Nachfolgend die Bedingung für die whileschleife(Haben wir falsch geraten?)
"""
while guess != secret:
guess = int(raw_input("Errate die Geheimzahl bis 10:"))
i... |
e69d4b0d739617711584d1985b89989e383763cc | Hash-Studios/algoking | /python/greatest_common_divisor.py | 687 | 4 | 4 | def greatest_common_divisor(a, b):
return a if b == 0 else greatest_common_divisor(b, a % b)
def gcd_by_iterative(x, y):
while y:
x, y = y, x % y
return x
def main():
try:
nums = input("Enter two integers separated by space ( ): ").split(" ")
num_1 = int(nums[0])
num_... |
69edd16c5d3eed00be694e931efb6bc93ceb38ad | szeitlin/data-incubator | /blah_algebra.py | 1,533 | 3.546875 | 4 | __author__ = 'szeitlin'
def make_blah(num):
"""blah = sum of square of digits mod 59
and
4 digit positive int -> int
>>>blah(6789)
(6**2 + 7 **2 + 8 **2 + 9 **2) mod 59
53
"""
#would be nice to do this with a list comprehension or map reduce fcns
a = 0
for i in str(num):
... |
76672e9f028628efa0e411ca98e2ae1358413d42 | GreenMarch/datasciencecoursera | /algo/heap/kth-smallest-element-in-a-sorted-matrix.py | 797 | 3.8125 | 4 | import heapq
class Solution:
def kthSmallest(self, matrix, k):
nums = []
for row in matrix:
for val in row:
nums.append(val)
heapq.heapify(nums)
return heapq.nsmallest(k, nums)[-1]
data = [[1,5,9],[10,11,13],[12,13,15]]
k = 8
print(Solution().kthSmallest... |
3ea7c63c5ff79bb362d24f0d9ff4d143a05bb3de | raririn/LeetCodePractice | /Solution/289_Game_of_Life.py | 2,112 | 3.53125 | 4 | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
self.board = board
self.l = len(board)
self.w = len(board[0])
status = [[0] * self.w for _ in range(self.l)]
f... |
41da291db485d72657a6dfc685d05935c9ad51dd | dupandit/Datastructure-and-Algorithms | /bubblesort.py | 648 | 3.640625 | 4 | n = int(raw_input().strip())
a = map(int, raw_input().strip().split(' '))
count = 0
sorted= False
while sorted == False :
## Track number of elements swapped during a single array traversal
numberofSwaps = 0
for j in range(n-1) :
##Swap adjacent elements if they are in decreasing order
... |
e39031a89464aa80b058443b2625fabbdc2997cb | clcocks/Year7_Python_S2 | /variables/how old/task.py | 140 | 3.90625 | 4 | name = input('what is your name? ')
print('hi '+ name)
age = input('how old are you?')
print(age+' is really old!')
print('bye '+ name)
|
965a4a16b374968f33734c92dfa2daf20a0992fe | shanksms/python_cookbook | /decorators/preserve_meta_data.py | 959 | 3.5 | 4 | import time
from functools import wraps
'''
Copying decorator metadata is an important part of writing decorators.
If you forget to use @wraps, you’ll find that the decorated function loses all sorts of useful information.
For instance, if omitted, the metadata in the last example would look like this:
>>> countdown... |
f55cd6e90820d728904e5ebba5a0b734624a9c37 | wensjuma/Msomi-App | /app/api/v1/models/profile_model.py | 1,571 | 3.609375 | 4 |
profile = []
class Profile(object):
""" profile data model to store data """
def __init__(self):
self.profile = profile
def create_profile(self,data):
profile = {
'user_id' : len(self.profile) + 1,
'username' : data['username'],
'telephone' : data['... |
4f5be43c67e71d3e664508f8803005cf4e32b880 | patrickmalg/aulas-python | /PYTHON-MUNDO 1/aula02-condicional.py | 295 | 3.953125 | 4 | idade = int(input("Digite a idade: "))
if idade < 16:
print("Não pode votar.")
elif idade >= 16 and idade < 18:
print("Pode votar, mas não é obrigatório.")
elif idade >= 18 and idade < 70:
print("É obrigatório votar.")
else:
print(" Pode votar, mas não é obrigatório.") |
99d28987a096dcbf843e5cced3a9f4cc1b5f78d5 | Alexsandra-kom/HW_Python | /HW8_Alexsandra_7.py | 1,150 | 4.15625 | 4 | # 7. Реализовать проект «Операции с комплексными числами». Создайте класс «Комплексное число», реализуйте перегрузку
# методов сложения и умножения комплексных чисел. Проверьте работу проекта, создав экземпляры класса (комплексные
# числа) и выполнив сложение и умножение созданных экземпляров. Проверьте корректность ... |
ca5839ecff60befd2eff0ed150e896d640be831c | ferociousmadman/python | /student-login/student.py | 5,126 | 4.03125 | 4 | def list_courses(id, c_list, r_list):
# ------------------------------------------------------------
# This function displays and counts courses a student has
# registered for. It has three parameters: id is the ID of the
# student; c_list is the course list; r_list is the list of
# class ro... |
b0714bcc4eda67b41925f1ff17c795e51a149715 | mayu0007/LeetCode | /155_MinStack.py | 3,718 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
155. Min Stack
Design a stack that supports
push, pop, top, and retrieving the minimum element in constant time.
"""
# Method 1: Use helper stack to store the current min element;
# Additional Space: O(N)
class MinStack_v1:
def __init__(self):
"""
initialize your data... |
fefcf7d3596478e69db68de85887bbd77be021ff | NajibAdan/project-euler | /problem_010.py | 615 | 3.71875 | 4 | import math
def isPrime(n):
if n==1:
return False
elif n<4:
return True
elif n % 2 ==0:
return False
elif n<9:
return True
elif n % 3 == 0:
return False
else:
r = math.floor(math.sqrt(n))
f = 5
while f<=r:
if n % f == 0... |
af51e62329dc13dc473bc1165bfaaed2680d204d | Legion-web/Refresh | /Calculator.py | 119 | 3.875 | 4 | no1=float(input("Enter your first number:"))
no2=float(input("Enter your second number:"))
result=no1+no2
print(result) |
afc0a31b99cac2ebdf9fb6ac85e3abd0e5471971 | Sandy4321/tensorflow_examples | /simple CNN.py | 3,213 | 3.765625 | 4 | """使用tensorflow实现一个简单的卷积神经网络"""
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
mnist = input_data.read_data_sets('MNIST_data/',one_hot=True)
sess = tf.InteractiveSession()
"""进行权重的初始化"""
def weight_variable(shape):
initial = tf.truncated_normal(shape,stddev=0.1)
return tf.V... |
ca78f2fa8fd365fa73ea40b98cc03ef84d9f0c8e | nandita-mehta/Python-Assignment | /Program_6.py | 194 | 4.0625 | 4 | def divisibility(x):
for i in range(0, x+1):
if i % 5 == 0 or i % 7 == 0:
yield i
n = int(input("Enter the number:"))
for i in divisibility(n):
print(i, end=", ")
|
350d2aaf2bfab570c87d37851d696e3bcddee6b9 | joseagb97/Tarea1GonzalezSoto | /tarea1.py | 2,532 | 4.03125 | 4 | def check_char(x):
if type(x) is not str: # Compara si la variable de entrada es string
print("No puede ingresar varoles de tipo int, array, float, clase...")
elif len(x) > 1: # Compara si solo se ingresó 1 solo caracter
print("Error: Solo puede ingresar una letra")
elif 64 ... |
c5bfcfe7c6b41d4b01171cc935e4722346886c66 | moman102/Python-Basis | /Math.py | 132 | 3.9375 | 4 | a = int(input(" a : "))
b = int(input(" b : "))
print(a + b)
print(a * b)
print(a // b)
print(a / b)
print(a ** b)
print(a % b)
|
d6c870e298f1953a572e56c505db466ea684d2f7 | kostur86/kasia_tut | /test_001/test_003.py | 2,022 | 3.796875 | 4 | #!env python3
"""
Draw a sprite in a PyGame window.
"""
import pygame
from pygame import K_ESCAPE, QUIT
# As long as this variable is True game will be running
active = True
# Some global variables
SCREEN_SIZE = 128
BKG_COLOUR = (255, 255, 255) # White
def read_input():
"""
Read user input and return stat... |
bdcf775633ba1fca1265f67a2a46c06a5c316c4a | webclinic017/Financial_Machine_Learning | /build_model/model_insights.py | 1,992 | 3.75 | 4 | """
Name : model_insights.py in Project: Financial_ML
Author : Simon Leiner
Date : 02.09.2021
Description: Get build_model insights by permutation importance
"""
import eli5
from eli5.sklearn import PermutationImportance
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ... |
87569c82f01514cf76417def49b6db8a00a9e023 | TechMaster/LearnAI | /LinearRegression/Keras/keras_linear1.py | 679 | 3.75 | 4 | # Theo ví dụ mẫu của https://machinelearningcoban.com/2018/07/06/deeplearning/
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
# 1. create pseudo data y = 2*x0 + 3*x1 + 4
X = np.random.rand(100, 2)
y = 2 * X[:, 0] + 3 * X[:, 1] + 4 + .2 * np.random.randn(100... |
499ae05233dee30a4b2dfadd1cdb5ea2842271ea | rlaboulaye/bofinger | /tools/simple-tokenizer.py | 723 | 3.6875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import fileinput
ignorelist = ('!', '-', '_', '(', ')', ',', '.', ':', ';', '"', '\'', '?')
def displayword(w):
if w != "":
print w
# print w.lower()
def handletail(w):
# print w
if(w == ""):
return
if(ignorelist.count(w[len(w)-1]) > 0):
handletail(w[0:len(w)-1])
... |
13197a4400b41eb7f8cb3a31d0b273b545388c0e | YuanchengWu/coding-practice | /problems/1.1.py | 379 | 3.8125 | 4 | # Is Unique: Implement an algorithm to determine if a string has all unique characters.
# What if you cannot use additional data structures?
def isUnique(s):
if len(s) > 128:
return False
seen = [None] * 128
for c in s:
val = ord(c)
if seen[val]:
return False
se... |
9846ed7e4675e1d810c0a141f3bf991e4232ba3e | JackKelly1/Rubiks-Cube | /Cubie.py | 2,551 | 3.65625 | 4 | class Cubie():
def __init__(self, x, y, z, lenc, colours):
self.x = x
self.y = y
self.z = z
# length of a cubie side
self.lenc = lenc
self.colours = colours
def show(self):
# sets the color used to draw lines and borders around... |
ba3356c5dca260222cdc7c6d2c6f16c124a3bb1d | xiaohaiguicc/CS5001 | /Course_case/2018_10_30/word_reverse.py | 286 | 3.859375 | 4 | import sys
from stack_linkedlist import Stack
def main():
stack = Stack()
in_string = input("Input a string:\n")
out_string = ""
for c in in_string:
stack.push(c)
while not stack.is_empty():
out_string += stack.pop()
print(out_string)
main() |
0cda415271ae3a8cef1bf338e8b47c52f2fb3157 | jibarra/advent-of-code | /2017/day3/day3.py | 9,851 | 4.25 | 4 | import math
# day3_input = 23
day3_input = 347991
"""
Each new 'square' is an odd number squared. So the first
is 1^2, the next is 3^2, then 5^2, etc.
In these scenarios, the max distance is at the diagonals. The
diagonals are a distance of 1 less than the number squared
for that particular square. The min distance ... |
498fcb32cbd75682e4b94ab6dde60d19f7a81c04 | pragmatizt/Intro-Python-I | /src/05_lists.py | 1,311 | 4.6875 | 5 | # For the exercise, look up the methods and functions that are available for use
# with Python lists.
x = [1, 2, 3]
y = [8, 9, 10]
# For the following, DO NOT USE AN ASSIGNMENT (=).
"""this is a good link for some list methods: https://lucidar.me/en/python/insert-append-extend-concatanate-lists/"""
# Change x so th... |
0c9fc9ac2724fa7b8d51392018e7a15ffd028c1b | deppwater/- | /17_二叉树的先序遍历中序遍历和后序遍历的递归实现.py | 2,864 | 4.09375 | 4 | """
三种遍历顺序的说明:
假设有一颗数的节点为1-7 即为一个三层的满二叉树
如果不考虑打印 那么递归函数来到树上节点的顺序为(当当前节点继续往下的时遇到空还会再走一遍当前节点):
1、2、4、4(左空)、4(右空)、2、5、5、5、2、1、3、6、6、6、3、7、7、7、3、1
如果把打印时机放在第一次来到这个节点的时候为先序遍历 第二次为中序遍历 第三次为后序遍历
先序遍历:1、2、4、5、3、6、7
中序遍历:4、2、5、1、6、3、7
后序遍历:4、5、2、6、7、3、1
"""
class Node(object):
def __init__(self, item):
... |
483c69aa28ee6ebcb482ad2e1ecda34c2e50c785 | AlexandruBurlacu/bv-algorithm | /tests/test_space_tagger.py | 1,094 | 3.5 | 4 | import unittest
from src import space_tagger
class TestSpaceTagger(unittest.TestCase):
def test_space_tagger_match(self):
space_dict = {
"Terra Obscura": "earth",
"Vulcan": "other planets",
"Counter-Earth": "other planets",
"Phaëton": "other planets",
... |
2d5e792e0b1876d607476ef77ba6bef719ee5af2 | poorvavm/practice-fun | /funNLearn/src/main/java/leetcode/algorithms/P101_P200/P200_NumberOfIslands.py | 1,671 | 3.75 | 4 | """
Tag: dfs, matrix
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands
horizontally or vertically. You may assume all four edges of the grid
are all surrounded by water.
Example 1:
... |
37eda9fedc8620023dbaf7e2c2e60dee040a0cb0 | mesapejarvis/pdsnd_github | /bikeshare.py | 7,248 | 4.09375 | 4 | import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name o... |
6e069f8a3bf94906263dc9b7a776f2766bab8cce | iTenki/Python-Crash-Course | /Chapter 1~11 Python 基础知识/alien.py | 1,489 | 3.75 | 4 | #简单的字典 使用字典 访问字典中的值
alien_0 = {'color': 'green', 'points': 5 }
print(alien_0['color'])
print(alien_0['points'])
new_point = alien_0['points']
print("You just earned " + str(new_point) + " points!")
#字典添加键-值对
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
#字典不关心键-值的顺序,只关心键-值的关系。
#分行对字典添加键-值
ali... |
fef1b9b939586d8116466664acb4cc401a865158 | Hutchby/chess | /src/game.py | 2,465 | 3.5625 | 4 | # TODO: modify h_turn in order not to let player move if it's not a correct move
# TODO: allow h_player to be player 1 & c_player to be player -1
# from src.gui import *
from src.ai import *
from src.pieces import *
player = -1
players = {}
ia_type = "viral"
difficulty = 3
def select_game_type():
global player... |
8cf7e3c243906a556c7b364ae8929db16f807e4b | pyziko/python_basics | /oop/private and Public.py | 442 | 3.90625 | 4 | class Player:
def __init__(self, name, age):
self._name = name
self._age = age
def run(self):
print('run')
def speak(self):
print(f"my name is {self._name}, and I am {self._age} years old")
player1 = Player("Ezekiel", 100)
# there's really no privacy in python we can sti... |
c53a874aed800389ef4a7d34eca70ca0fe5f7cbe | gh4683/PythonWorkshop | /ListsTuplesDicts.py | 484 | 4.15625 | 4 | #List Ex: A list of the breakfast items in your kitchen
breakfast = ['Cereal', 'Milk', 'Eggs', 'Waffles', 'Coffee']
print(breakfast)
print(breakfast[3])
#Tuples Ex: Months in the year
months = ('jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec')
print(months)
#Dictionaries Ex:... |
7e367d81835a5feaaa895a58a905fb806bffa107 | YMSPython/Degiskenler | /Lesson1/OperatorlerOrnekler.py | 1,726 | 3.8125 | 4 | # Örnek 1) Disaridan alinan
# iki sayının toplamiyla farkinin birbirine bolumunden kalanin sonucu kactir?
sayi1 = int(input("Lütfen birinci sayiyi giriniz : "))
sayi2 = int(input("Lütfen ikinci sayiyi giriniz : "))
toplam = sayi1 + sayi2
fark = sayi1 - sayi2
mod = toplam % fark
print("Islem sonucu :", mod)... |
e7deb4de032c109bfc552e93888ce0e74da6147d | jke-zq/my_lintcode | /Tweaked Identical Binary Tree.py | 779 | 4 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
"""
class Solution:
"""
@param a, b, the root of binary trees.
@return true if they are tweaked identical, or false.
"""
def isTweakedIdentical(self, a, b):
... |
e69ba129d1d7f449f5544ec5e1cf89c75ce644c0 | mkuehn10/Intro-to-Interactive-Programming-in-Python | /01+_RPSLS.py | 3,220 | 4.3125 | 4 | # GUI-based version of RPSLS
###################################################
# Student should add code where relevant to the following.
import simplegui
import random
#global variables
player_wins = 0
computer_wins = 0
ties = 0
#helper functions
def init():
global player_wins, computer_wins, ties
player... |
923a350a9e6d9dbe0d51897501610c21904b9c37 | vitaliksokil/pythonlabs | /lab9/lab91.py | 4,218 | 3.59375 | 4 | import random
def blackjack(num_of_players):
if num_of_players > 4 or num_of_players < 2:
exit('Maximum of players is 4 and minimum is 2')
blackjack_dictionary = {
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'T... |
9788d401a09a2e32c73641eed8883b25adf1f596 | twitu/bot_programming | /state_manager.py | 1,402 | 3.71875 | 4 | class StateManager:
""" State Management Module """
def __init__(self, unit_id, state_id=None):
"""
Initializes the State Manager with the unit type and initial state
Args:
unit_id: Unit Type of AI
state_id: Starting state (optional)
"""
if... |
af7044d66ea51fd8f39e168fee7864cb5c13546c | Dzhevizov/SoftUni-Python-Fundamentals-course | /Functions - More Exercises/02. Center Point.py | 416 | 4.03125 | 4 | import math
def find_closest_point(x1, y1, x2, y2):
distance1 = (x1 ** 2 + y1 ** 2) ** 0.5
distance2 = (x2 ** 2 + y2 ** 2) ** 0.5
if distance1 <= distance2:
return f'({math.floor(x1)}, {math.floor(y1)})'
else:
return f'({math.floor(x2)}, {math.floor(y2)})'
X1 = float(input())
Y1 = fl... |
399ddf157e0dd11a540b76bd624b7d0230f342c0 | jainjayesh24/Ch-9-Flow-of-Control | /p.9.py | 315 | 4.375 | 4 | char=input("Enter your character: ")
if char>="A" and char<="Z":
print("Your character is an Uppercase")
elif char>="a" and char<="z":
print("Your character is an Lowercase")
elif char>="0" and char<="9":
print("Your character is a digit")
else:
print("You have entered special Character")
|
8cec860a090b6d0945baafc30a35be4b4d98bf7c | ssooda/pajang | /ksy/300제/2ndWeek4.py | 4,938 | 3.703125 | 4 | #241
import datetime
print(datetime.datetime.now())
#datetime모듈의 datetime객체??의 now함수
#242
now = datetime.datetime.now()
print(type(now))
#243
now = datetime.datetime.now()
for i in range(5,0,-1) :
print(now - datetime.timedelta(days=i))
#244
now = datetime.datetime.now()
print(now.strftime("%H:%M:%S"))
#245
pr... |
ab5ff80cd41fadc1e85636a9a3bd3ac44ec8e553 | VieVie31/bonapity | /examples/simplest.py | 2,392 | 3.78125 | 4 | from bonapity import bonapity
@bonapity
def add(a: int, b: int = 0) -> int:
""" Add `a` with `b` if `b` is provided, otherwise returns `a` only.
Example:
------------------
>>> add(4, 5)
9
"""
return a + b
@bonapity
def concatenate(s1: str, s2: str) -> str:
""" Return the concatenat... |
3d71406fa45c294b773acd9761a8b261045cc5af | IgorEM/Estudos-Sobre-Python | /variaveis.py | 254 | 3.53125 | 4 | # -*- coding: utf-8 -*-
var1 = 1 #variavel inteira
var2 = 1.1 #variavel float
var3 = "Eu sou uma string" #variável string
var4 = True #variavel boleana, True-False.
var5 = False
print(var1)
print(var2)
print(var3)
print(var4)
print(var5)
|
d8c0ef258b53c53db625a4499bdf1549fb7dd461 | BinDannyMa/chem991e | /02_introduction_to_python_part_ii/class_assignment_solution.py | 151 | 3.765625 | 4 | nums = input("Enter your list: ")
smallest = 10000000000
for n in nums.split(","):
if int(n) < smallest:
smallest = int(n)
print(smallest)
|
1e60fd9b8f70e47b6c41de92e44d57d71cf79dc1 | AgileMathew/AnandPython | /Module II/pgm35.py | 526 | 3.75 | 4 | """Problem 35: Write a program to count frequency of characters in a given file. Can you use character frequency to tell whether the given file is a Python program file, C program file or a text file?"""
def word_frequency(words):
frequency={}
for w in words:
frequency[w]=frequency.get(w, 0)+1
return frequency
... |
129ae1bf16926ddf4c4657500731dac25afdb5e5 | Mega-Barrel/Quiz-Game | /questions/Geography_question.py | 466 | 3.8125 | 4 | def geography_question():
question = []
question.append(['Which continent is the largest?', 'Asia'])
question.append(['Which of the Seven Wonders is located in Egypt?', 'Pyramid of Giza'])
question.append(['What is the capital of New Zealand?', 'Wellington'])
question.append(['Which desert is the l... |
007645adf46f0a3b5ca6aa35c08125377f438857 | bgoonz/UsefulResourceRepo2.0 | /_PYTHON/DATA_STRUC_PYTHON_NOTES/python-prac/mini-scripts/python_Cummulative_Sum.txt.py | 86 | 3.546875 | 4 | import numpy as np
arr = np.array([1, 2, 3])
newarr = np.cumsum(arr)
print(newarr)
|
84fd443b056c3c08ef99a7179b12e7c77a95d02d | Dharadharu/hi | /factors.py | 81 | 3.53125 | 4 | fa=int(input())
for i in range(1,fa+1):
if fa%i==0:
print(i,end=" ")
|
494e5bc7b7a2693005a2691d3e99c618e2652869 | ffadullgu/programaciondecomputadores | /codigo/python3/11_comprenhension.py | 1,217 | 4.125 | 4 | ## El siguiente procedimiento:
#squares = []
#for x in range(10):
#squares.append(x**2)
#print(squares)
## Se puede escribir como:
#squares = list(map(lambda x: x**2, range(10)))
#print(squares)
## O como:
#squares = [x**2 for x in range(10)] # list comprenhension
#print(squares)
## El siguiente procedimiento:
#... |
6ab9187e927160155db78dd756bebc81f9b7fc6d | PedroOspina17/academy | /Week-0/matrix.py | 12,037 | 3.59375 | 4 |
class Matrix(object):
def __init__(self, data):
self.numRows = len(data)
self.numColumns = len(data[0])
self.data = data
@staticmethod
def convertSetToList(data):
return [list(item) for item in data]
def clone(self):
return Matrix(self.data)
d... |
0ae10072426575f3785a2bf431f4b61de28d46ae | Johnathan-Xie/Siena-Youth-Center-Code-Examples | /Day3/card_picker_class_proj3.py | 1,584 | 3.921875 | 4 | import random
class Card:
def __init__(self, value, suit):
self.value = value
self.suit = suit
def get_value(self):
return self.value
def get_suit(self):
return self.suit
def __str__(self):
return self.value + ' of ' + self.suit
def __repr_... |
85e5fd2576dc040cd3330f3a7e92eda77f4a614c | tapishr/Interview-Prep | /priya/interviewbit/Number of 1 bits.py | 295 | 3.609375 | 4 | class Solution:
# @param A : integer
# @return an integer
def numSetBits(self, A):
count = 0
while(A!=0):
if(A&1):
count+=1
A = A>>1
return count
# Question at : https://www.interviewbit.com/problems/number-of-1-bits/
|
c139e47059479fbb71179d7905ac4193bb1f8f46 | psh89224/Bigdata | /01_Jump_to_Python/Chapt03/124-2.py | 282 | 3.5625 | 4 | #coding=cp949
prompt="""
1.Add
2.Del
3.List
4.Quit
Enter number:"""
number=0
while True:
print(prompt,end='')
number=int(input())
if number ==4:
break #while ᰡ Ǵ 2 ̻϶
else:
if number ==5:
break
|
539997a066346e122873fb28429ed3ed145b7cfe | vadim-ivlev/pytest | /hello.py | 654 | 4.21875 | 4 | #%%%
print("hello")
print('hello1')
print('hello2')
#%%%
a=5
b=6
c=a+b
print(a+b)
# %%
# %%
# import an excel file into a dataframe and save it to sqlite3 database
def import_excel_to_sqlite():
import pandas as pd
import sqlite3
# read the excel file into a dataframe
df = pd.read_excel('data.xlsx'... |
57a93c185a3f8e21a86dbc2ece77a0a75edcecd1 | shenhuaze/leetcode | /python/symmetric_tree.py | 857 | 3.875 | 4 | # @author Huaze Shen
# @date 2020-01-12
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def is_symmetric(root):
if root is None:
return True
return is_equal(root.left, root.right)
def is_equal(left, right):
if left is None and ... |
97214616b4b0a4ffb8cc46dd6eae1305a6f8c87a | whyj107/Algorithm | /Puzzle/012_Sqrt.py | 1,236 | 3.671875 | 4 | # 제곱근의 숫자
# 문제
# 제곱근을 소수로 나타내었을 때 0 ~ 9의 모든 숫자가 가장 빨리 나타나는 최소 정수를 구해 보세요.
# 단 여기서는 양의 제곱근만을 대상으로 합니다.
# 정수 부분을 포함하는 경우와 소수 부분만 취하는 경우 각각에 대해 모두 구해 보세요.
# 힌트
# 포인트는 소수의 '유효 숫자'를 의삭하고 있느냐가 되겠습니다.
# 소수를 다루는 형에는 float형이나 double형 등이 있습니다.
from math import sqrt
# 정수 부분을 포함하는 경우
i = 1
while True:
i += 1
# 소수점을 제거하... |
6d7aa904a771c55c590c10dbd67f10c697cfd94d | ko9ma7/cse_project | /coding practice/Programmers/Skill Check/Level2/2.py | 618 | 3.515625 | 4 | def solution(heights):
answer = []
re_heights = list(reversed(heights))
for i in range(len(re_heights)):
for j in range(i+1, len(re_heights)):
print(re_heights[i], re_heights[j])
if re_heights[i] < re_heights[j]:
answer.append(j)
break
... |
43c03d8297634cb68e0204f0824db13244572422 | MrHamdulay/csc3-capstone | /examples/data/Assignment_6/krmtsi001/question4.py | 800 | 4.0625 | 4 | marks=input("Enter a space-separated list of marks:\n").split() #is is to make what the user has inputted into a list for manipulation
first_class=0
upper_second=0 #line 2 to 5 making each grade a category
lower_second=0
third_class=0
fail=0
for grade in marks:
if eval(grade)<50: #looping through ... |
f18b46c4a3dff8b2f1ae9073956aefda9ab30690 | gutus/100DaysPythonAngelaWu | /Day02/Day02Section01.py | 874 | 3.96875 | 4 | # TIP CALCULATOR
# Untuk menghitung tagihan per orang beserta tip nya
print("Selamat datang, mari kita hitung tagihan tiap orang.")
tagihan = int(input("Berapa besaranya tagihan bill total? "))
tip = int(input("Berapa besaran tip untuk pelayan, 10, 12 atau 15% ? "))
orang = int(input("Berapa banyaknya orang yg akan dit... |
7a5153a4f2bd556a0ff448953e9329ec8745b236 | sarenvs/guvi | /9.py | 74 | 3.59375 | 4 | b=input()
a=len(b)
ba=b[::-1]
if b==ba:
print(b[:a-1])
else:
print(b)
|
78f98af6b91e927c6d4ecca88f216137eeba2452 | terasakisatoshi/pythonCodes | /iterators/iter_next.py | 205 | 3.65625 | 4 | def count():
c = 0
while True:
yield c
c += 1
gen = count()
print(next(gen)) # 0と表示
print(next(gen)) # 1と表示
print(next(gen)) # 2と表示
print(next(gen)) # 3と表示 |
3b7d8e19dbe705b573b3a71ad17ce7d95bbd0ce2 | bupt-yl/TF | /homework-copy/zy1.py | 2,103 | 3.546875 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import cv2
mnist = input_data.read_data_sets("MNIST_data/",one_hot = True)
# print("输入数据的shape",mnist.train.images.shape)
# import pylab
im = mnist.train.images[1]
# im1 = mnist.train.images[2]
#print(im)
#im = im.reshape(28,28)
#im... |
da86fb792fbf2552bf3b7c4d180d366b85453c0b | tlind15/Algorithms_python | /search_algorithms/src/run_times2.py | 1,610 | 3.6875 | 4 | from random import randint
from rand_array import rand_array
from binary_search import *
from linear_search import *
from math import log2
print("Input a size: ")
size = int(input()) #takes in input
while size <= 0: #ensuring a valid size
print("Not a valid size input a size: ")
size = int(input())
array = r... |
e4f3946f5c863136f4aa0077ca979c718658947e | Nanofication/PersonalChatbot | /Interface.py | 649 | 3.65625 | 4 | """
Chatbot interface
Run this script to interact with the chatbot
"""
import Brain
def interactWithChatbot(user_input):
"""
Processes the user_input and come up with the correct response
"""
memory = Brain.parseUserInput(user_input)
if memory != None:
print Brain.processMemory(memory)... |
55985dcc0db14580d4e59b23945a2d2fa27781e3 | Lovelyjha/GeeksforGeeks | /2.Easy/Anagram.py | 168 | 3.671875 | 4 | t=int(input())
for _ in range(t):
a,b=input().split()
if set(a)==set(b) and len(a)==len(b):
print("YES")
else:
print("NO")
|
3cecd0940a755266e48efbf4e2f4eb21fc81617c | arminale/ProjectEuler | /102_Triangle_Containment/p102.py | 1,087 | 3.75 | 4 | # https://projecteuler.net/problem=102 Triangle Containment
# For any 3 non collinear points ABC:
# The sum of the areas of the three triangles OAB, OAC, and OBC is equal to the area of a triangle ABC if and only if
# O is contained in ABC
# The area of a triangle can be calculated from the coordinates of its vertices... |
76198dfa6b068a4451886a7f12c057cf6906e9e0 | DiamondGo/leetcode | /python/GrayCode.py | 771 | 4.03125 | 4 | '''
Created on 20160501
@author: Kenneth Tse
The gray code is a binary numeral system where two successive values differ in only one bit.
Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.
For example, g... |
5362d1c07ac02b5859d350530c3e84b76eae358c | ribal-aladeeb/state-space-search | /node.py | 2,685 | 3.6875 | 4 | from __future__ import annotations # in order to allow type hints for a class referring to itself
from typing import List, Tuple
from board import Board
import numpy as np
class Node:
def __init__(self,
move: dict = None,
parent: Node = None,
simple_cost: int =... |
05434c09a84d35b809ab74e5c24d73f777012a48 | stgleb/problems | /python/tree/ddl_to_tree.py | 1,517 | 3.953125 | 4 | """
Convert sorted ddl to binary search tree
"""
class Node(object):
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
def find_mid(left, right):
slow = left
fast = left
while fast != right:
fast = fast.next
if fast == right:
... |
3a0f4e68e62982755c98dffc8e0f14e63c9a0fbe | wp-lai/xpython | /code/month_day.py | 526 | 3.96875 | 4 | """
Task:
Convert date from day of the month to day of the year.
>>> month_day(1988, 60)
(2, 29)
"""
def month_day(year, day):
daytab = [[0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
[0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]]
leap = 1 if year % 4 == 0 and year % 100 != 0 or... |
506434e071543e78caeb394af28b980dbd41e922 | rexarabe/Python_projects2 | /string_methode/020_casefold.py | 141 | 3.875 | 4 | """In this example we will use method that will lower case the text"""
txt = "Hello, And Welcome To My World!"
x = txt.casefold()
print(x)
|
1cb3381142bcd6dc5d62711104037226922c9021 | lisettemalacon/MOSTECEECS2019 | /MOSTEC EECS work 2/collision.py | 545 | 3.546875 | 4 | def collision(coord1,w1,h1,coord2,w2,h2):
x1 = coord1[0]
y1 = coord1[1]
x2 = coord2[0]
y2 = coord2[1]
width1 = x1 + w1
height1 = y1 + h1
width2 = x2 + w2
height2 = x2 + h2
x_intersection = [x for x in list(range(x1,width1 + 1)) if x in list(range(x2,width2 + 1))]
y_int... |
548880a6cbb881dadfad5db2370eff60ccd96121 | ashukrishna100/Python_Data_Analysis | /numpy_tutorial.py | 2,009 | 3.984375 | 4 |
# coding: utf-8
# In[1]:
import numpy as np
# In[2]:
## determine size and shape of an array
array1=np.array([(2,3,4,5),(1,0,3,6)])
print(array1.size)
print(array1.shape)
# In[3]:
## Reshape an array
array1=np.array([(2,3,4,5),(1,0,3,6)])
print(array1.reshape(4,2))
# In[4]:
## Datatype
print(array1.dtyp... |
97ddfd2f21b8ff623531d6d7010019ea682096f6 | 77Ladybug/python-converter | /inputccyconvv1.py | 418 | 3.84375 | 4 | def conv_CHF_in_EUR(CHF):
EUR = CHF * 0.88
return "As per today " + str(CHF) + " chf equal " + str(EUR) + " eur"
user_input = input("Please enter amount of CHF you want to convert in EUR: ")
result = (conv_CHF_in_EUR (float(user_input) * 0.88))
print(result)
if float(user_input) <= 100000:
print... |
ea11d79e06f98b6f7abdd6fd9113483c506075f1 | prabhamerlin/Analysis-of-COVID-cases-in-different-states-of-India | /convert_csv_to_json.py | 597 | 3.5 | 4 | import json # This is for working on JSON data
import csv # This is for working on .csv FILE
with open ("Population.csv", "r") as f:
reader = csv.reader(f)
next(reader)
data = []
for row in reader:
data.append({"Rank" : row[0],
"State/UT" : row[1],
... |
c5681d2393a23eea2b3f9b53a53300e17b30c6ba | rodrigobn/Python | /Lista de exercicio 5 (Lista e Matrizes)/ex02.py | 235 | 4.0625 | 4 | """
2 - Faça um Programa que leia um vetor de 10 números reais e mostre-os na ordem inversa.
"""
lista = [1,2,3,4,5,6,7,8,9,10]
if lista == []:
print("Lista vazia")
else:
for i in range(len(lista)-1, -1, -1):
print(lista[i])
|
b46b30517fdc59d3569d27f08d82d7e049ef8982 | blackrain15/Python_Basics | /07_Dictionary/Sample Problem 2.py | 692 | 3.828125 | 4 | from datetime import datetime, timedelta
start_day = input()
days_to_reach = int(input())
start_date = input()
week_days = {'Monday':1, 'Tuesday':2, 'Wednesday':3, 'Thursday':4, 'Friday':5, 'Saturday':6, 'Sunday':7}
start_date = datetime.strptime(start_date, '%d-%m-%Y')
start = week_days.get(start_day)
start = star... |
fba0caa7aeffc2bebf1b4ea94a15289dcb595902 | southpawgeek/perlweeklychallenge-club | /challenge-056/lubos-kolouch/python/ch-2.py | 757 | 4 | 4 | #!/usr/bin/env python
""" https://perlweeklychallenge.org/blog/perl-weekly-challenge-056/
Task 2
You are given a binary tree and a sum, write a script to find if the tree has a path such that adding up all the values along the path equals the given sum. Only complete paths (from root to leaf node) may be consid... |
101068ab3872236ce5bbffa778febe5fc49ce58d | daianasousa/POO | /LISTA DE EXERCÍCIOS/Semana02_postagem_extra_Q01.py | 3,352 | 3.890625 | 4 | class Radio:
#Atributos
ligado = True
cor = None
faixa = None
peso = None
altura = None
volume = 0
estacao = None
volume_max = 0
volume_min = 0
#Construtores
def __init__(self, ligado=False, volume_max=100, volume_min=0):
self.ligado = ligado
self.volume_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.