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 |
|---|---|---|---|---|---|---|
c9a6b379df20d169f7b760e741fa14c3eb3c1a4d | happyrabbit456/hellopython | /src/coroutinedemo/send_demo.py | 767 | 3.75 | 4 | '''
最初的yield只能返回并暂停函数,并不能实现协程的功能。后来,Python为它定义了新的功能——接收外部发来的值,这样一个生成器就变成了协程。
每个生成器都可以执行send()方法,为生成器内部的yield语句发送数据。此时yield语句不再只是yield xxxx的形式,还可以是var = yield xxxx的赋值形式。它同时具备两个功能,一是暂停并返回函数,二是接收外部send()方法发送过来的值,重新激活函数,并将这个值赋值给var变量!
'''
def simple_coroutine():
print('-> 启动协程')
y = 10
x = yield y
print(... |
f140aa19dbcb788490760bc5fe08ff92be61bb73 | happyrabbit456/hellopython | /src/coroutinedemo/yield_demo2.py | 609 | 3.859375 | 4 | '''
yield的语法规则是:在yield这里暂停函数的执行,并返回yield后面表达式的值(默认为None),直到被next()方法再次调用时,从上次暂停的yield代码处继续往下执行。当没有可以继续next()的时候,抛出异常,该异常可被for循环处理。
'''
# 下面是通过for循环不断地使fib生成下一个数,实际上就是不断地调用next()方法。
def fib(n):
a, b = 0, 1
i = 0
while i < n:
yield b
a, b = b, a+b
i += 1
if __name__ == '__main__':
... |
f9b4fbf32266dd17ff96586117c8e126cd1fa54e | Liam-Pigott/python_crash_course | /01-ObjectsAndDataStructures/Numbers.py | 284 | 3.9375 | 4 |
# basic arithmetic
print(2 + 1)
print(7 + 4)
print(3 / 2)
print(7 / 4)
print(7 % 4)
print(2 ** 3)
print(0.1 + 0.2 - 0.3)
a = 5
print(a)
a = a + a
print(a)
print(type(a))
a = 30.1
print(type(a))
my_income = 100
tax_rate = 0.1
print("My taxes: {}".format(my_income * tax_rate))
|
23eb4288c74348e898b5e987f8755ebf2cc2db62 | Liam-Pigott/python_crash_course | /11-Advanced_Python_Modules/defaultdict.py | 769 | 4.15625 | 4 | from collections import defaultdict
# defaultdict is a dictionary-like object which provides all methods provided by a dictionary but takes a first argument (default_factory)
# as a default data type for the dictionary. Using defaultdict is faster than doing the same using dict.set_default method.
# A defaultdict wil... |
aad7fec002bf6717bb2a7e6389c964ec6344cd4a | Liam-Pigott/python_crash_course | /02-Statements/control_flow.py | 1,768 | 4.15625 | 4 | # if, elif and else
if True:
print("It's True")
else:
print("False")
loc = 'Bank'
if loc == 'Work':
print('Time to work')
elif loc == 'Bank':
print('Money maker')
else:
print("I don't know")
name = 'Liam'
if name == 'Liam':
print("Hello Liam")
elif name == 'Dan':
print('Hi Dan')
else:
... |
1e50523fd73b73a3a77eae5a985b0e8bf0700915 | Liam-Pigott/python_crash_course | /03-Functions/lambdas.py | 913 | 3.84375 | 4 | def square(num):
return num ** 2
my_nums = [1, 2, 3, 4, 5]
for item in map(square, my_nums):
print(item)
print(list(map(square, my_nums)))
def splicer(mystring):
if len(mystring) % 2 == 0:
return 'EVEN'
else:
return mystring[0]
names = ['Liam', 'Chloe', 'Ben']
# pass the function... |
b39a21d0b6aceed613b6b710f04fd5c1eba485fe | Liam-Pigott/python_crash_course | /12-Advanced_Objects_DataStructures/advanced_numbers_and_strings.py | 792 | 3.78125 | 4 | ############################
# ADVANCED NUMBERS #
############################
print(hex(12))
print(bin(1234))
print(bin(128))
print(bin(1024))
print(2**4 == pow(2,4))
print(abs(-13245))
print(round(3.1))
print(round(3))
print(round(3.9))
print(round(3.141592, 2))
############################
# ADVANCE... |
3453685d8c9b2cfba1dc4bdc454b06ee13e16268 | channerduan01/gomoku | /AlphaZero_Gomoku-master/game.py | 10,259 | 3.875 | 4 | import numpy as np
import tkinter
class Board(object):
"""
board for the game
"""
def __init__(self, **kwargs):
self.width = int(kwargs.get('width', 8))
self.height = int(kwargs.get('height', 8))
self.states = {} # board states, key:move as location on the board, value:player a... |
6f2d440071bdacdb59adc4409561dfb6b63683d3 | ksannedhi/practice-python-exercises | /Ex11.py | 618 | 4.34375 | 4 | '''Ask the user for a number and determine whether the number is prime or not. (For those who have forgotten, a prime number is a number that has no divisors.).
You can (and should!) use your answer from Exercise 4 to help you. Take this opportunity to practice using functions.'''
def find_prime_or_not(num):
d... |
bbe653b8a4f428b0c7abc5ede7939455abdf2a06 | ksannedhi/practice-python-exercises | /Ex15.py | 532 | 4.4375 | 4 | '''Write a program (using functions!) that asks the user for a long string containing multiple words.
Print back to the user the same string, except with the words in backwards order. For example, say I type the string:
My name is Michele
Then I would see the string:
Michele is name My'''
def reverse_words(inp... |
50ca688b88f9b6fa091fd02c8bfad6640c4cca8a | pzinz/sep_practice | /07_sets.py | 398 | 3.859375 | 4 | animals = {'cat', 'dog', 1}
print(animals)
print(type(animals))
print('cat' in animals)
print('fish' in animals)
animals.add('fish')
print(len(animals))
animals.add('cat')
print(len(animals))
animals.remove('cat')
print(len(animals))
#loops
for idx, animal in enumerate(animals):
print('#%d: %s' % (idx + 1, animal)... |
993033a674b3d7a44cc8aacb6f9910d84c8b4531 | pzinz/sep_practice | /22_HarvardX_w01_03.py | 2,199 | 4.25 | 4 | # Static typing mean that the type checking is performed during compile time
# dynamic typing means that the type checking is performed at run time
# Varible, objects and references
# x = 3 ; Python will first create the object 3 and then create the variable X and then finally reference x -> 3
# list defined as foll... |
d82c82e29fe664b568610fefa5c92bda2dcc4b6e | Azucrim/Testes-Toodoo-Alan-Maida | /Teste Toodoo Alan Maida/atv13.py | 438 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 8 21:32:14 2021
@author: aland
"""
import sys
import numpy as np
i=int(input("Quantidade de Linhas:"))
z=int(input("Quantidade de Colunas:"))
m=[]
for x in range(i):
m.append([])
for y in range(z):
m[x].append((y+1)*(x+1)... |
6f7f3f2cee60a9d7a5df4069adc7ed6c6724087c | aisonet/Solution | /Palindrome.py | 686 | 3.9375 | 4 | DEFAULT_TEXT = "aabaa"
def palindrome(s):
results = set()
text_length = len(s)
#print text_length
for idx, char in enumerate(s):
# Check for longest odd palindrome(s)
start, end = idx - 1, idx + 1
while start >= 0 and end < text_length and s[start] == s[end]:
resul... |
ca025ff977935b48ffe64d3241acc231fd83e08a | aisonet/Solution | /CountingBinarySubstring.py | 448 | 3.625 | 4 |
import sys
import os
# Complete the function below.
def counting(s):
allLetter=list(s)
count=0
str=''
n=0
maxi=len(allLetter)
#print maxi
for n in range(0,maxi):
print n
print allLetter[n], allLetter[n+1]
if allLetter[n]!=allLetter[n+1]:
count=+1
... |
cc869964b4024b5c3952105b95d9fbcf2c1c5368 | Nukemenonai/holbertonschool-interview | /0x00-lockboxes/0-lockboxes.py | 721 | 4.03125 | 4 | #!/usr/bin/python3
""" this file contains the canunlock all main function
and its subordinate recursive function"""
def canUnlockAll(boxes):
""" returns true if all boxes can be unlocked else false"""
boxescp = boxes
foundkeys = []
unlockRecursively(boxescp, 0, foundkeys)
for llave in foundkeys:
... |
762280b8b5e1c54582b4fb85ee99b973031edf3c | JSchuurmans/P1_Facial_Keypoints | /models.py | 7,607 | 3.671875 | 4 | ## TODO: define the convolutional neural network architecture
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
# can use the below import should you choose to initialize the weights of your Net
import torch.nn.init as I
class Net(nn.Module):
def __init__(sel... |
66926c2849a081364bcdf16dcb828431785e576d | Mani-Saketh/Basic-Statistics-with-Python | /mean 1.py | 125 | 3.609375 | 4 | def mean(my_data):
return float(sum(my_data)) / max(len(my_data), 2)
my_data=[1,2,3,4,5,6,7,8,9,10]
print(mean(my_data))
|
1918397d74b690aaf737479a25ff1e038f896003 | cxdtotsj/algorithm_base | /py_base/structure_algorithm/bf.py | 1,536 | 3.734375 | 4 | # -*- coding: utf-8 -*-
# @Data : 2021-03-26
'''
BF算法 Python
* 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
*
* 示例 1:
*
* 输入: haystack = "hello", needle = "ll" 输出: 2
*
* 示例 2:
*
* 输入: haystack = "aaaaa", needle = "bba" 输出: -1
'''
class SolutionDef:
def str_s... |
2e464bd439cd11ffb08740efd3b8393ab4579523 | davehedengren/pairsTournament | /strategies/alexStrategies.py | 3,678 | 3.5625 | 4 | class FixFoldStrategy:
"""This strategy folds every time there is a small card available."""
def __init__(self, N=3):
self.N = N
def play(self, info):
if info.bestFold(self.player)[1] > self.N:
return 'Hit me'
else:
return 'fold'
class RatioFoldStrategy:
... |
db3a0ee9692d9829e4a69584b12e343d1fbc5c35 | malekhnovich/PycharmProjects | /untitled1/MidtermPractice/STRING_EXAMPLES.py | 284 | 3.859375 | 4 | s='hello'
print("This is the first rendition of "+s)
s+=" and goodbye"
print("This is the second rendition of "+s)
s="til next time"
print("This is the third rendition of "+s)
s1=s[:5]
print("This is the fourth rendition of "+s1)
s2=s[::2]
print("This is the fifth rendition of "+s2)
|
ec68888812b15838438f33bcb97c68e3dac62ba2 | malekhnovich/PycharmProjects | /Chapter5_executing_control/Chapter6_dictionaries/tuple_example.py | 1,336 | 4.59375 | 5 | '''
IF DICTIONARY KEYS MUST BE TYPE IMMUTABLE WHILE LIST TYPE IS MUTABLE
YOU CAN USE A TUPLE
TUPLE CONTAINS A SEQUENCE OF VALUES SEPERATED BY COMMAS AND ENCLOSED IN PARENTHESIS(()) INSTEAD OF BRACKETS([])
'''
#THIS IS A TUPLE BECAUSE THE PARENTHESIS ARE ROUND RATHER THAN SQUARE
#SQUARE PARENTHESIS WOULD BE A LIST
#THE ... |
2f991334cca1cfcd8c36d43deec46e94373d1eb7 | belka-j/CSCA2-PROJECT | /hangman.py | 10,153 | 4.03125 | 4 | #the logic behind the define functions(line 1 to line 63) was used from lab 8
#we modified them to fit into our code
#importing the file so we can read and write into it
import csv
with open("Score.List.csv") as reader_file:
# Read the file
reader = csv.reader(reader_file)
# Make it a list type, so it's e... |
14b09b637899e0b491c6c883ebb8ffb3128ce917 | vipin08/DS-Algo | /Tree.py | 1,569 | 4 | 4 | class Node:
def __init__(self,data):
self.left = None
self.right = None
self.val = data
def inOrder(root):
if root:
inOrder(root.right)
print(root.val)
inOrder(root.left)
def preOrder(root):
if root:
print(root.val)
preOrder(root.left)
... |
411af0c23d2d91b6ff5977547dd914a401118583 | justinleebehnke/LinearAlgebraMatrixTool | /__main__.py | 5,434 | 4.25 | 4 | def main():
# 1. (Replacement) Replace one row by the sum of itself and a multiple of another row.
# 2. (Interchange) Interchange two rows.
# 3. (Scaling) Multiply all entries in a row by a nonzero constant.
# I should change it to be in these terms
matrix = [
[1.0, 2.0, 1.0, 0.0],
... |
f1f23d187fc395cd7b33302aba360d546f0ca391 | s0l0l0b0/DATASTRUCTURE | /josephus_O(log(n)).py | 346 | 4 | 4 | # Josephus problem when size of step is 2(fixed).
# Returns position of survivor among a
# circle of n number of prisoners and every second
# prisoner being killed
def josephus(n):
p = 1
while p <= n:
p *= 2
return (2 * n) - p + 1
n = int(input("How many prisoners: "))
print ("The surviving ... |
53f92b613f7d8a00bb3f4a46e0956e1a0b9d0e3c | MuirlandOracle/hacksoc-bot | /libs/colours.py | 776 | 3.578125 | 4 | #!/usr/bin/python3
"""
Title: Colours
Type: Helper Module
Purpose: Prettify the Terminal Output
Last Edited By: Sam
Last Updated: 17/05/21
"""
import sys
class Colours:
red = "\033[91m"
green = "\033[92m"
blue = "\033[34m"
orange = "\033[33m"
purple = "\033[35m"
end = "\033[0m"
... |
b42ace7c28ad5224af073ba6703128d6f80bfae5 | ses1142000/python-30-days-internship | /day 10 py internship.py | 1,313 | 4.3125 | 4 | Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> import re
>>> string = "a-zA-Z0-9"
>>> if re.findall(r'/w',string):
print("the string contains a set of char")
else:
print("the string does... |
e74aa996aa46f0682a4ed8946c2e69e2d2010cbd | SubikManandhar/sqlite | /sqlite.py | 4,209 | 3.796875 | 4 | import sqlite3
import json
import requests
response = requests.get("https://raw.githubusercontent.com/younginnovations/internship-challenges/master/programming/petroleum-report/data.json")
# def jprint(obj):
# # create a formatted string of the Python JSON object
# text = json.dumps(obj, sort_keys=True, indent... |
cd40b1284c75d06e02e558762f9deeb4e1ef254b | Palatio93/prueba | /prueba.py | 69 | 3.515625 | 4 | print("Hi")
for x in range(3):
print(x)
# Linea 6 para cambiar
|
b054a7650777c84701251a12388f24196b438f06 | wenilton/linguagemdeprogramacao | /numero menor.py | 231 | 3.859375 | 4 | n1 = int(input('Digite o primeiro valor: '))
n2 = int(input('Digite o segundo valor: '))
n3 = int(input('Digite o terceiro valor: '))
menor = n1
if menor > n2:
menor = n2
if menor > n3:
menor = n3
print ('Menor: %d ' %menor) |
9e90c8c11d9352283cd731aec48de88038b64f88 | JanusClockwork/LearnPy | /Py3Lessons/python_ex05.py | 1,597 | 4.125 | 4 | name = 'Janus Clockwork' #according to my computer lol
age = 26
height = 65 #inches. Also, why is height spelled like that. I before E except after C? My ass.
weight = 114 #lbs. also I AM GROWIIINNNG
eyes = 'gray' #'Murrican spelling
teeth = 'messed up'
hair = 'brown'
favePet = 'cats'
faveAnime = 'Yowamushi Pedal'
fav... |
825f433ce89304248ea8c292ebb232df375792cc | SHILPA-GRACE-V/chatbot | /livechatbot.py | 800 | 3.640625 | 4 | #Import packages
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
#Import data to train the chatbot
bot=ChatBot('CHOTTU') #define chatbot
bot.set_trainer(ChatterBotCorpusTrainer)#define trainer - set algorithm
bot.train('chatterbot.corpus.english') #Train... |
75e0218f0cdb8da460335dc9ad7942a93489281f | paullgdc/adventofcode_2019 | /8/main.py | 865 | 3.640625 | 4 | from functools import reduce
WIDTH = 25
HEIGHT = 6
image = input()
def split_image(image, dim):
return [image[i * dim: (i + 1) * dim] for i in range(len(image) // dim)]
def count_digit(layer, digit):
return sum((elem == digit for elem in layer))
def merge_layers(layer_top, layer_bot):
return "".join([
... |
97e33a679068f8b0114bcb7d7556e60a7fd322c5 | anantsrivastava30/CTCI | /ch2circularLL.py | 2,381 | 3.859375 | 4 | import os
import sys
from chapter2 import LinkedList
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
class CircularLinkedList:
def __init__(self, head=None):
self.head = head
def __iter__(self):
current = self.head
while current... |
549f5afa052256d4eb588c85bf01964f2fcdf521 | Ran4/alcc | /sortimentdownloader.py | 4,962 | 4.03125 | 4 | """Is used to handle the download of the sortiment file to disk, parsing it
and finally pickling the results.
"""
import urllib2
import os.path
import time
import pickle
SORTIMENT_XML_FILENAME = "sortiment.xml"
ARTICLES_PICKLE_DUMP_FILENAME = "articles.pickle"
def update_if_needed(silent=True):
"""Will download a... |
51e60e55e595033542f6efbbab8b3a593239e09f | okhee/BOJ | /level_9_primeNum/1_1978.py | 486 | 3.6875 | 4 | import math
maxNum = 1000
isPrimeList = [True] * (maxNum - 1) # 2 ~ maxNum
for i in range(2, math.ceil(math.sqrt(maxNum))):
for j in range(i+1, maxNum+1):
if (j % i == 0):
isPrimeList[j-2] = False
def isPrime(n):
if(n < 2):
return False
return isPrimeList[n-2]
dummy = input()
n... |
58ffef3aca0a30fd700082144f27d3d535b73408 | okhee/BOJ | /level_17_stack/6_17298.py | 765 | 3.5 | 4 |
# A = [3, 2, 1, 3, 1, 9, 8]
"""
bottom
8, -1
9, -1
1, 9
3, 9
2, 3 -> 3 is leftmost bigger number than 2
lost info about 9
3, -1 -> 9
stack
8
9
3
새 숫자가 같거나 크면 stack에서 계속 pop,
그 다음 새 숫자를 push
"""
N = int(input())
A = list(map(int, input().split()))
nge = []
stack = []
elem = A.pop()
stack.append(elem)
nge.a... |
69d4510f000ecdaed313435dd25c120265b608df | okhee/BOJ | /level_9_primeNum/2_2581.py | 615 | 3.796875 | 4 | import math
maxNum = 10000
isPrimeList = [True] * (maxNum - 1) # 2 ~ maxNum
for i in range(2, math.ceil(math.sqrt(maxNum))):
for j in range(i+1, maxNum+1):
if (j % i == 0):
isPrimeList[j-2] = False
def isPrime(n):
if(n < 2):
return False
return isPrimeList[n-2]
M = int(input())... |
d389a579ea1360932b5af127018b9b35e66ecc3b | paluchasz/Python_challenges | /interview_practice_hackerank/Arrays/Minimum_Swaps.py | 2,389 | 4.21875 | 4 | '''Find minimum number of swaps in an array of n elements. The idea is that the min
number of swaps is the sum from 1 to number of cycles of (cycle_size - 1). E.g
for [2,4,5,1,3] we have 2 cycles one between 5 and 3 which is size 2 and requires 1 swap
and one between 2 4 and 1 which is of size 3 and requires 2 swaps. S... |
cba55fed10f53f69c2860cf020507a736827532e | paluchasz/Python_challenges | /interview_practice_hackerank/Warm_up_problems/Counting_Valleys.py | 961 | 4.28125 | 4 | '''This program has a series of Ds and Us, we start at sea level and end at sea level, we
want to find the number of valleys, ie number of times we go below sea level (and back to 0)'''
import math
import os
import random
import re
import sys
# Complete the countingValleys function below.
def countingValleys(n, s):
... |
f05bd834cb62f22aa1009dd5caf090bbbf9544b5 | paluchasz/Python_challenges | /arrays/PrintingElementsOfArrayInReverse.py | 73 | 3.546875 | 4 |
arr = [2,3,4,5,6]
for i in range(len(arr)-1,-1,-1):
print arr[i]
|
f898ea81030496a045ae3b69978bb728081e615d | AntonotnaWang/GrabCut-python | /grabcut_GUI.py | 7,683 | 3.671875 | 4 | '''
Interactive Image Segmentation using GrabCut algorithm.
Please first select a picture.
Draw a rectangle around the object using mouse right button.
then press the following keys to draw mask using mouse left button.
Key 'n' - To update the segmentation
Key '0' - To select areas (adding masks) of sure background
... |
9442c85bb68abfdea021eac668bb25cc7ac5528f | GithuiVictor/SkaeHub-Developer-Program-Boot-Camp | /DAY 4/Challenge_5/challenge5.py | 181 | 3.671875 | 4 | import itertools as it
def infinite_data(iter):
return it.cycle(iter)
# Dictionary
result = infinite_data({1: 'Skae', 2: 'Hub', 3: 'Developer'})
for k in result:
print(k) |
4c739e2ed78113aa549290dfc5ea4024fa54ee2d | Its-S1d/Coldplay-Concept-Website | /Images/madlibsgame.py | 251 | 3.921875 | 4 | character_name = input("Enter your name :")
character_age = input("Enter a number :")
color = input("Enter a color :")
print("My name is " + character_name)
print('I am ' + character_age + " years old")
print("My favourite color is " + color)
|
022986d06c8c46a43e3c0d1275751f197bfb93d3 | neuneed/PythonLearn | /class002/help.py | 85 | 3.5 | 4 |
def convert_to_ascii(text):
return " ".join(str(ord(char)) for char in text)
|
c20d648c3206eb9c2507c5d9df693f096b009fbe | cehan-Chloe/Lintcode | /61SearchForARange.py | 1,371 | 3.703125 | 4 | class Solution:
"""
@param A : a list of integers
@param target : an integer to be searched
@return : a list of length 2, [index1, index2]
"""
def searchRange(self, A, target):
# write your code here
if A is None or len(A) == 0:
return[-1,-1]
start = 0
... |
f6ec5cedde7dd8c688f05e0974002d77b849fce8 | iathanasy/notes | /Algorithm/查找-插值查找.py | 961 | 3.859375 | 4 | # ֵ
* Ҫҵļ¼ģε
* ڶֲңΨһͬDzֵÿδӦ mid ʼ
mid = low + (high - low) * (key - arr[low]) / (arr[high] - arr[low])
key: Ǽֵ
arr:
low: ͽDZ
high: ߽DZ
mid: Ӧmid
# ʵ
def insert_value_search(collection, low, high, value):
if low > high or value < collection[0] or value > arr[len(arr) - 1]:
return -1... |
e3c471725d3d9b5feff1789cee61b6cff095da32 | iathanasy/notes | /Algorithm/排序-交换排序-冒泡.py | 910 | 3.796875 | 4 |
# ̫ˣ˵
def bubble(arr):
length = len(arr)
for i in range(length):
for x in range(i, length):
if arr[i] > arr[x]:
temp = arr[i]
arr[i] = arr[x]
arr[x] = temp
arr = [5, 6, 8, 7, 6, 3, 2, 4, 0, 1, 9]
bubble(arr)
print(arr)
# ðŻ
* ijһεûз, ǰ
... |
451bc18ec6b679f421ff318e0f64f62a3d675b12 | Rabbids13/Pengecek_harga_sembako_kedua | /Modul 4 masi gagal/hf/Domino.py | 4,297 | 3.96875 | 4 | class Domino(object):
def pembeliansembako():
print ("Program pengecekan harga barang di toko")
def ayam (jumlahayam='30.000/Kg'):
print ("Berapa Kilo ayam yang anda mau cek harganya : ")
jumlahayam = float(input())
totalayam = 30000 * jumlahayam
... |
2faf60dc78a471e1f3962d9861fb48bf0404a9ca | tekkoloji/AlgoritmaAnalizi | /sinav/matris.py | 280 | 3.640625 | 4 | a=[[2,3],[4,5]]
b=[[1,4]]
for x in range(0,len(a)):
list=a[x]
for y in range(0,len(b[0])):
toplam=0
for z in range(0,len(list)):
#print list[z]+" "+b[z][y]
toplam=toplam+list[z]*b[z][y]
print toplam,
print " "
|
860a0c5b034deeadf81e75966bab5bf529eca505 | rodrigopc-bit/treinamento-maratona | /I. MMI/teste.py | 137 | 3.53125 | 4 | t=int(input())
for i in range(t):
a=input().split(" ")
tuple(a)
for item in a:
int(item)
print(min(a)+" "+max(a)) |
671550eae1ac21abec2ed4c40e1f837f79680e14 | Jinah1/lastName_pythagorean | /evenOrOddPt2.py | 155 | 4.3125 | 4 | x=int(input("Enter an integer and see if it is even or odd:"))
if x % 2 ==0:
print(x ,"is an even number")
else:
print(x ,"is not an even number")
|
9ec1cab03fd968e343e828430f15f93289aeb766 | leovinogradov/simple-python-multiprocessing | /example1.py | 567 | 3.59375 | 4 | import simpleMultiprocessing as multiprocessing
# Use fibonacci function for testing
def Fibonacci(n):
if n<0:
print("Incorrect input")
# First Fibonacci number is 0
elif n==1:
return 0
# Second Fibonacci number is 1
elif n==2:
return 1
else:
return Fibonacci(n-1... |
3608c44ab2d527502b864be1e13af76a126a55f7 | ekaterinaYashkina/simulated_annealing_PMLDL | /Task2/utils.py | 1,659 | 4.15625 | 4 | import math
from geopy.distance import lonlat, distance
"""
Calculates the distance between the two nodes using euclidean formula
neighbours - list of tuples, nodes coordinates
first, second - indices of elements in neighbours list, between which the distance should be computed
"""
def euclidean_dist(first, second... |
9feee87b52cb434afa8aefa5cde05d7a18ba3c05 | mhstk/Information_Retrieval_project | /heap.py | 3,198 | 4.21875 | 4 | class Max_Heap:
# initializing the constructor with arr (array that we have to convert into heap). The default value is None([])
def __init__(self, arr=[]):
# Initializing the heap with no elements in it
self._heap = []
# If the array by the user is not empty, push all the eleme... |
48850fc4794cad6e6a780731fd1f13baf33a5592 | julian0818/Python | /Ejercicio1.py | 236 | 3.765625 | 4 | edad = int(input("Ingrese su edad"))
print("Su edad actual: " + str(edad))
edadFuturo = int(input("Cuantos años desea agregar?"))
edadTotal = edad+edadFuturo
print("Dentro de " + str(edadFuturo) + "usted tendrá " + str(edadTotal)) |
a5c03adc06e0008b177f4dea643b0f2c9353cff9 | Shubhashis-coder/GOOGLE-KICK-START-2021-ROUND-B-SHUBHASHIS-MONDAL | /3 (Consecutive Primes).py | 781 | 3.515625 | 4 | import sys
input = sys.stdin.readline
def is_prime(n):
if n < 2:
return False
for i in range(2,n+1):
if i * i > n:
return True
if n % i == 0:
return False
return True
def solve1(Z):
p = 2
best = 0
for i in range(3, Z):
if is_prime(i):
if i * p > Z:
break
best = i * p
p = i
return be... |
3c306859509160aa8621c30def77df856c7f7074 | arjunmantri/hackerrank | /contests/capitalize.py | 246 | 3.890625 | 4 | #https://www.hackerrank.com/contests/pythonist3/challenges/capitalize
S = input()
out = ""
isSpace = True
for e in S:
if isSpace:
e = e.upper()
isSpace = False
if e == " ":
isSpace = True
out += e
print(out)
|
c5be152df04b4f46d886acf301f2fea65200b627 | Alberto-Oliveira-Barbosa/Desafios | /Python2/1001.py | 76 | 3.53125 | 4 | # -*- coding: utf-8 -*-
A = input()
B = input()
print("X = %i" % (A+B))
|
fac59941ebc61cf7a72ec8eb13586820d7dc084c | Alberto-Oliveira-Barbosa/Desafios | /Python2/1070.py | 166 | 3.78125 | 4 | # -*- coding: utf-8 -*-
n = int(input())
if n%2==0:
for x in range(n+1,n+12,2):
print x
else:
for x in range(n, n+12, 2):
print x
|
e49cba25e8c39366c2ba1b46ade481ff0d8e7676 | Alberto-Oliveira-Barbosa/Desafios | /Python2/1002.py | 101 | 3.609375 | 4 | # -*- coding: utf-8 -*-
pi = 3.14159
raio =input()
area = pi * (raio**2)
print("A=%.4f"%area)
|
2521b21e4669dbeff65473951c0ce421957e5aea | Alberto-Oliveira-Barbosa/Desafios | /Python2/1096.py | 134 | 3.796875 | 4 | # -*- coding: utf-8 -*-
for x in range(1,10,2):
print ("I=%i J=7" % x)
print ("I=%i J=6" % x)
print ("I=%i J=5" % x)
|
bf14ace6b3232f0476414077f57a63cb4f91a87c | Alberto-Oliveira-Barbosa/Desafios | /Python2/1048.py | 500 | 3.515625 | 4 | # -*- coding: utf-8 -*-
s = float(input())
rea = 0.0
perc = ""
if s <= 400:
rea = (s * 15.0)/100
perc = "15 %"
elif s >400 and s <=800:
rea = (s * 12.0)/100
perc = "12 %"
elif s> 800 and s <= 1200:
rea = (s * 10.0)/100
perc = "10 %"
elif s>1200 and s <= 2000:
rea = (s * 7.0)/... |
2777693aa4cf312cda822957ca15f94ff2a9fada | Lynch08/MyWorkpands | /Code/Labs/LabWk7/overwrite.py | 354 | 3.515625 | 4 | #Write a function that takes in a number and overwrites a file with that number (count.txt). test it and check that the file has been changed
#Author: Enda Lynch
#REF: Labsheet for Wk07, Andrew Beatty
filename = ".\Topic07files\count.txt"
def writeNumber (number):
with open (filename, "wt") as f:
f.write... |
c4e6962f828436c536428674006e0cc442ec82da | Lynch08/MyWorkpands | /Code/Labs/LabWk2/notequal.py | 206 | 3.875 | 4 | #Author: Enda Lynch
#true or false - A is equal/or not equal to B
#input integers
A = int(input('Enter a number:'))
B = int(input('Equal to?' ))
#print if statment is true or false
print ('Answer is ',(A==B)) |
8aa19aece7c856c53348b9f18a895d8a6999f2bc | Lynch08/MyWorkpands | /Code/Labs/LabWk4/isEven.py | 249 | 4.1875 | 4 | # Author: Enda Lynch
# tell the user if they input an odd or even number
number = int(input("Enter an integer:"))
if (number % 2) == 0 :
print ("{} is an even number" . format(number))
else:
print ("{} is not an even number" . format(number))
|
38400be20795cf6cbdb634a9e6ad55ee7c719f8d | Lynch08/MyWorkpands | /Code/Labs/LabWk4/guess3.py | 568 | 4.25 | 4 | # generates random number for user to guess
# Author: Enda Lynch
# import random module and set limit between 1 and 100
import random
numberToGuess = random.randint(0,100)
#string for user
guess = int(input("Please guess the number between 1 and 100:"))
##'while' sets loop and 'if' and 'else' give prompts
while gue... |
7311aa6c044af79f5c0b08319e246a6bfb777f27 | Lynch08/MyWorkpands | /Code/Labs/LabWk7/doesFileExist.py | 671 | 3.765625 | 4 | #Write some code to check if the file exists. To do this we will need to import
#os.path and use the isfile() function
#Enda Lynch
#REF Andrew Beatty Lab Wk7
import os
filename = ".\Topic07files\count.txt"
def writeNumber(num): #create function to write the number returned from readNumber
with open... |
df8184f3fb9f59899881d65da52500a050962e64 | Lynch08/MyWorkpands | /Code/Labs/LabWk9/myFunctions.py | 568 | 3.515625 | 4 | #In this lab we are going to make a function called Fibonacci in a module called myFunctions to show error handeling
#Author: Enda Lynch
#Credit: Andrew Beatty (LabWk 9)
def fibonacci (number):
return[]
return7 = [0,1,1,2,3,5,8]
return11 = [0,1,1,2,3,5,8,13,21,34,55]
assert fibonacci(7) == return7, 'incorrect re... |
adb1b11db3ebe9418db19a807d9dbdc0a0b8723e | Lynch08/MyWorkpands | /Code/Labs/LabWk5/student.py | 458 | 4.0625 | 4 | #Programme to store students name, courses and grades
#Author: Enda Lynch
student = {
"name": "Mary",
'courses': [
{
'courseName:': 'Programming',
'grade:': 45
},
{
'courseName:': 'History',
'grade:': 99
}
]
}
print ("Student... |
2618d88acba70b47d7b374bcd1864ab3eeed50cf | Lynch08/MyWorkpands | /Code/Labs/LabWk3/div.py | 347 | 4.125 | 4 | #Author: Enda Lynch
# Division programme with remainder
#enter values using inputs to devide on integer by another
X = int(input('Enter number: '))
Y = int(input('Divided by: '))
# '//' gives divides the integers and '%' gives the remainder
B = X//Y
C = X%Y
#display work
print("{} divided by {} is equal to {} rema... |
8935b6a65d80e8cbcfc0742fb1deea95e1d3006d | elmahdim/pystart | /strings.py | 826 | 3.71875 | 4 | lang = 'python'
skills = [lang, 'javascript', 'ruby']
print('single quoted')
print("double quoted")
print("""Multi
Lines.""")
print('Hello from, ' + 'the other side!')
# String Methods
print(lang.lower())
print(lang.upper())
print(lang.capitalize())
print(' python '.strip())
print(lang.isalpha())
print(lang.isdigi... |
7a2ed190c3d27d635a021014ee974f3873516d16 | tparackal/Test-Code | /test.py | 202 | 4.21875 | 4 | def numType(x):
a = "none"
if x < 0:
a = "negative"
if x > 0:
a = "positive"
if x == 0:
a = "zero"
return a
num = input("Enter a number: ")
result = numType(num)
print("Number is " + result) |
15eaaf67d7ffdf2fff665d26e9b0d621fab64811 | pykili/py-204-hw1-Sophia179 | /task_3/solution_3_2.py | 173 | 3.59375 | 4 | a=''
alphabet='abcdefghijklmnopqrstuvwxyz'
itog=''
for i in range(10):
word=input()
a=a+word
for i in range(26):
if alphabet[i] in a:
itog=itog+alphabet[i]
print(itog)
|
a4b94d07c019eba3b5d741dd14ebd0b478b107a5 | CptObviouse-School-Work/SDEV220 | /module3/6.5.py | 354 | 4.21875 | 4 | '''
Jesse Duncan
SDEV 220
Programming Assignment: 6.5
Due June 17, 2018
'''
def displaySortedNumbers(num1, num2, num3):
numbers = [num1, num2, num3]
numbers.sort()
print("The sorted numbers are " + str(numbers[0]), str(numbers[1]), str(numbers[2]))
num1, num2, num3 = eval(input("Enter three numbers: "))
... |
bb90ab5f1e40dee795f826f8831d1c7b9b23555b | CptObviouse-School-Work/SDEV220 | /module2/3.4.py | 216 | 4.1875 | 4 | '''
Jesse Duncan
SDEV 220
Exercise 3.4
Due June 10, 2018
'''
import math
side = eval(input("Enter the side: "))
area = (5 * (side * side)) / (4 * math.tan(math.pi / 5))
print("The area of the pentagon is " + str(area))
|
b89ad4519aa213d563301604959b34ff2a94bf40 | CptObviouse-School-Work/SDEV220 | /week3/ticTacToe.py | 3,500 | 3.859375 | 4 | '''
Jesse Duncan
SDEV 220
Programming Assignment: 11.9 - Tic Tac Toe
Due July 1, 2018
'''
class Game():
def __init__(self):
self.turns = 9
self.player = "X"
self.gameList = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
while self.turns > 0:
self.displayGameBoard()
... |
2e225d616432eabeddd4a1913cbc82b7013f7fd2 | CptObviouse-School-Work/SDEV220 | /module2/4.15.py | 1,400 | 4.125 | 4 | '''
Jesse Duncan
SDEV 220
Exercise 4.15 Game: Lottery
Due June 10, 2018
'''
import random
# Generate a lottery number
lottery = random.randint(0, 999)
# Prompt the user to enter a guess
guess = eval(input("Enter your lottery pick (three digits): "))
#Get digits from lottery
removeLastDigit = lottery // 10
firstDigit... |
54333583ec300c0e6aee7f559ce026ccb49e3999 | CptObviouse-School-Work/SDEV220 | /week5/numberOfUpperCase.py | 477 | 3.65625 | 4 | '''
Jesse Duncan
SDEV 220
Programming Assignment: Numbef of Upper Case - 15.13
Due July 8, 2018
'''
def main():
userInput = input("Enter a string: ")
print("The number of uppercase letters is: ", countUpperCase(userInput))
def countUpperCase(s):
return countUpperCaseHelper(s, 0)
def countUpperCaseHelper(... |
921e24380c609cd1ee9b3e8c56373253cfd34958 | SophiyaMaharjan/python7am | /whileloop.py | 199 | 3.8125 | 4 | x=1
sum = 0
sumodd= 0
while x<=50:
if x%2 == 0:
sum = sum+x
else:
sumodd = sumodd+x
x+=1
print('sum of even numbers {} and sum of odd numbers {}'.format(sum, sumodd))
|
1d05422ef7d919d380a130e363e3763a253a484f | Leoads99/Programing-Language---II | /ex6.py | 217 | 4.03125 | 4 | def divisores (n):
soma = 0
for i in range (1, n+1):
if n % i == 0:
soma += i
return soma
num = int(input('Informe um número: '))
print("Soma dos divisores: " ,divisores(num)) |
3077281533422b02b13784230c270c8c25b3e3d5 | Leoads99/Programing-Language---II | /exemplo3.py | 819 | 3.703125 | 4 | '''
Criar uma classe Aluno
- Atributos: ra, nome, email, lista de notas.
- Métodos: inserir_nota, calcular_media
'''
class Aluno:
def __init__(self, ra, nome, email):
self.ra = ra
self.nome = nome
self.email = email
self.lista_notas = []
def inserir_nota(self, nota):
s... |
6b406d1ea76d8a30b1a3dd315eb2656335d1b2fe | Leoads99/Programing-Language---II | /ex1.1.py | 2,605 | 4.1875 | 4 | """
Ex 01 -
Preencha uma lista com 10 números digitados pelo usuário e exiba:
a - O maior número da lista
b - O menor número da lista
c - a média dos números contidos na lista
d - todos os números menores do que a média calculada no item anterior
cont = 0
lista = []
while cont <10:
numeros = int(input('Digi... |
97967a5a065bd475f9ff9039f77771d8fdfe97ad | MSmirnov3517/algorithms_and_data_structure | /1.8.py | 468 | 4.03125 | 4 | # Определить, является ли год, который ввел пользователь, високосным или не високосным.
y = int(input(' Введите год - '))
if y % 4 == 0:
if y % 100 == 0:
if y % 400 != 0:
print('обычный год')
else:
print('високосный год')
else:
print('високосный год')
else:
p... |
eab26f9443b40ea34f9ec9d6d86973f9ff730431 | uaawaw/git_projekt | /max_min.py | 554 | 3.6875 | 4 | a1 = int(input())
a2 = int(input())
a3 = int(input())
print (a1,a2,a3)
print (a1*a2*a3)
print (a1+a2-a3)
if (a1>=a2 and a1>=a3) and (a2>=a3):
print ('\n',a1,'\n',a3,'\n',a2)
elif (a1>=a2 and a1>=a3) and (a3>=a2):
print ('\n',a1,'\n',a2,'\n',a3)
elif (a2>=a1 and a2>=a3) and (a1>=a3):
print ('\n',a2,'\n',a3,... |
2ccc2e40b907d65bc7b74ec62e07d1fc83ec69f7 | snigdhasen/myrepo | /examples/ex14.py | 356 | 3.515625 | 4 | '''
Working with keyword argument
'''
def fn1(n1, n2, *args, **kwargs):
print('type(args) is', type(args))
print('args contain', args)
print('type(kwargs) is', type(kwargs))
print('kwargs contain', kwargs)
def main():
fn1(100, 200, 12, 34, 56, x=300, name='Vinod', email='vinod@vinod.co', phone='97... |
0d3ee274b09f506103419a3d5e2d443c0d38b8c0 | snigdhasen/myrepo | /examples/ex11.py | 1,084 | 3.890625 | 4 | '''
various file reading techniques
'''
import json
def read_file_1(filename):
file = open(filename, 'rt')
for line in file.readlines(): print(line, end='')
file.close()
def read_file_2(filename):
file = open(filename, 'rt')
# the 'file' object itself is iterable; no need to call .readlines()
... |
73b3c6c9e4baa48941846a7fa0c542b83cd1556f | hibfnv/Python-learning | /car_class.py | 330 | 3.546875 | 4 | class Car():
def __init__(self,make, model, year):
self.make = make
self.model = model
self.year = year
def get_description(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name
new_car = Car('Audi', 'A6', 2018)
print(new_car.get_desc... |
b92050a43e7859e3fa58a04e7e72b5b98982e740 | hibfnv/Python-learning | /func_parm.py | 311 | 4.125 | 4 | #!/usr/bin/python
# -*- coding:utf-8 -*-
# Author: Eason
def str(var1,*vartuple):
print var1
for var in vartuple:
print var
print "=" * 20
print "输出定义的变量:"
print "=" * 20
str(10)
print "=" * 20
print "输出所有未定义的变量:"
print "=" * 20
str(20,30,40)
print "=" * 20 |
5b69117a67d6eb545bd98a3b277667d57a1a7a0d | hibfnv/Python-learning | /error_exception.py | 300 | 3.984375 | 4 | #!/usr/bin/env python
# use while true
while True:
try:
x=input('Enter the first number:')
y=input('Enter the second number:')
value=x/y
print 'x / y =',value
except Exception,e:
print 'Invalid input:',e
print 'Please try again.'
else:
break
|
aa0f740db91b07e54cd78009a988558b29466fcf | hibfnv/Python-learning | /fibonacci.py | 167 | 3.859375 | 4 | #!/usr/bin/env python
# define fibs
fibs = [0, 1]
num = input('Enter number for fibo_math: ')
for i in range(num - 2):
fibs.append(fibs[-2] + fibs[-1])
print fibs
|
558e88e7558efe4649d65d0b8eb552c02439db78 | hibfnv/Python-learning | /rectangle.py | 298 | 3.8125 | 4 | #!/usr/bin/env python
class rectangle:
def __init__(self):
self.width=0
self.height=0
def setsize(self,size):
self.width,self.height=size
def getsize(self):
return self.width,self.height
r=rectangle()
r.width=10
r.height=5
print r.getsize()
r.setsize((150,100))
print r.width
|
b15ff60c1ffd05efc129edc92bb3470296a8e0a5 | hibfnv/Python-learning | /function_session01.py | 1,037 | 3.71875 | 4 | #!/usr/bin/env python
# Begin script by python
# define variables in use
dict={}
dict['first']={}
dict['middle']={}
dict['last']={}
# initializa info
def init(data):
data['first']={}
data['middle']={}
data['last']={}
dict={}
init(dict)
print dict
# add info below:
me='Green George Will'
dict['first']['Green... |
48ff5ca00e42c1906a766fa949fb378a782abd28 | rpaudel1/public_private_attributes_OOP | /public_private_attrb.py | 533 | 3.890625 | 4 | class Mammal:
def __init__(self, eyes, ears, limbs):
self.eyes = eyes # not right approach, public
self._ears = ears # also not right approach
self.__limbs = limbs # private, the way we do
def get_eyes(self):
return self.eyes
def get_ears(self):
return self._ears
def get_limbs(self):
return self.__li... |
cd8247f4cccce79bf8003b545161ddae540a48ee | ChuckWoodraska/AdventOfCode | /2019/day4/day4.py | 1,060 | 3.53125 | 4 | def check_number(num):
num = str(num)
dup_check = False
ascend_check = True
for c in range(len(num) - 1):
if num[c] == num[c + 1]:
dup_check = True
elif num[c] > num[c + 1]:
ascend_check = False
return bool(dup_check and ascend_check)
def check_number2(num):... |
4b102785e2f16c37053d8f70c64984889a19a0a2 | gy6274858/python100days | /day3/exe3.py | 479 | 3.703125 | 4 | """
输入三条边长,如果能构成三角形就计算周长和面积
"""
import math
a = float(input('请输入第一条边长: '))
b = float(input('请输入第二条边长: '))
c = float(input('请输入第三条边长: '))
if (a + b > c) & (a + c > b) & (b + c > a):
l = a + b + c
p = l / 2
s = math.sqrt((p * (p - a)*(p - b)*(p - c)))
print('该三角形的面积是%.2f,周长是%.2f' % (s, l))
else:
pr... |
1709893a582b9d5a265e0cca9884b3346e8408ad | suleymancakiroglu/MyPythonExamples | /mathprob4.py | 198 | 4.09375 | 4 | print("Please enter your info!")
name =input("Name :")
surname =input("Surname :")
number =input("Number :")
print("Your name is:{}\nSurname is:{}\nAnd number is:{}".format(name,surname,number)) |
0e787597cb8df659feab66ea35f2d590cb5df025 | suleymancakiroglu/MyPythonExamples | /userlogin.py | 564 | 3.890625 | 4 | print("""**************
Users Login
**************
""")
sys_userName ="suleyman61"
sys_passWord ="denverwade"
userName =input("Username :")
passWord =input("Password :")
if (userName == sys_userName and passWord != sys_passWord):
print("Incorrect username or password!")
elif (userName != sys_userNam... |
d07c546a58df5af7c9bb6d9c58043a659c276582 | suleymancakiroglu/MyPythonExamples | /regisplayer.py | 341 | 3.5 | 4 | print("Player Registration Program")
name = input("Player's Name :")
surname = input("Player's Surname :")
team = input("Player's team :")
infos =[name,surname,team]
print("Infos are recording...")
print("Player's Name: {}\nPlayer's Surname: {}\nPlayer's Team:{}".format(infos[0],infos[1],infos[2]))
print("... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.