blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
1da503cceacec73acde73f4b761fff190400370c | robinson-1985/mentoria_exercises | /lista_ex1.py/exercicio2.py | 309 | 4.25 | 4 | # 2. Faça um programa que receba três notas, calcule e mostre a média aritmética.
nota1 = float(input("Informe a nota 1: "))
nota2 = float(input("Informe a nota 2: "))
nota3 = float(input("Informe a nota 3: "))
media = (nota1 + nota2 + nota3) / 3
print(f"A média aritmética das notas é: {media:.2}") |
5a1a5eb8847a0ccb2ec8cdf911bf4630694bdb5b | robinson-1985/mentoria_exercises | /lista_ex1.py/exercicio1.py | 400 | 4.15625 | 4 | ''' 1. Faça um programa que receba quatro números inteiros, calcule e mostre a soma
desses números. '''
numero1 = int(input("Digite o primeiro número: "))
numero2 = int(input("Digite o segundo número: "))
numero3 = int(input("Digite o terceiro número: "))
numero4 = int(input("Digite o quarto número: "))
soma = numer... |
21ce8a1d40d37b0df6c9b5cffeaa2a758d4bf78d | kamiloCervantes/mentorias_genmotion | /ejercicios mentorias/ejerciciomatrizterrenos.py | 486 | 3.703125 | 4 | matriz_acidez = []
matriz_oxido_fosforo = []
zonas = 3
for i in range(zonas):
print("Ingrese los valores de acidez")
entrada = input()
lista = entrada.split(" ")
matriz_acidez.append(lista)
print(matriz_acidez)
print(matriz_acidez[0][2])
for i in range(zonas):
print("Ingrese los valores de oxido d... |
37cb87dffbf4da9fa703f6f30f599fd1de2b5c78 | renshareck/ReuseCodeRepository | /singleton/singleton.py | 872 | 3.6875 | 4 | import time
import threading
# 打印缓冲区锁
# print buffer lock
print_lock = threading.Lock()
class Singleton():
_instance_lock = threading.Lock()
def __init__(self):
time.sleep(1)
pass
@classmethod
def instance(cls):
Singleton._instance_lock.acquire()
if n... |
a59b07caadde0b03231cb05df1d596e9e335bb46 | Yuu-taremayu/J5-SoftwareDesign | /player.py | 1,200 | 3.515625 | 4 | import random
class PLAYER:
# init player status
def __init__(self, order):
self.name = str(order + 1)
# player's position
self.x = 0
self.y = 0
# player's dice
self.dice = None
# some status
self.money = 0
self.muscle = 0
self.... |
46a3e98a58c7187f63a260bf1ed7fd7d84b01a19 | AnkitShaw-creator/practice_python | /Lapindromes.py | 631 | 3.515625 | 4 | def check_lapin(s):
if len(s) % 2 == 0:
set1 = [x for x in s[0:len(s)//2]]
set2 = [x for x in s[len(s)//2:]]
if sorted(set1) == sorted(set2):
return "YES"
else:
return "NO"
else:
set1 = [x for x in s[0:len(s)//2]]
set2 = [x for x in s[len(... |
3e53f4a2e2d8b6b7c4c41ca58c48ab0dcbbca85d | AnkitShaw-creator/practice_python | /chef_and_pairs.py | 511 | 3.546875 | 4 |
def count_pairs(n, l):
pairs = []
c =0
for i in range(0, n):
for j in reversed(range(n)):
if l[i] % 2 == 0 and l[j] % 2 != 0 and i<j:
pairs.append("{}, {}".format(l[i], l[j]))
c += 1
# print(pairs)
return c
if __name__ == "__main__":
output ... |
32e2ed9170e4f946fb1beb779aa8a95c701d3cfe | AnkitShaw-creator/practice_python | /the_block_game.py | 267 | 3.5625 | 4 |
def reverse(k):
s = [x for x in k[::-1]]
return "".join(map(str, s))
if __name__ == "__main__":
for _ in range(int(input())):
n = input()
if n == reverse(n):
print("wins")
else:
print("loses") |
934977e4373752a72f803161bbb8ea0ee9dd8221 | AnkitShaw-creator/practice_python | /primality_test.py | 456 | 3.953125 | 4 | import math
"""
1 ≤ T ≤ 20
1 ≤ N ≤ 100000
"""
def checkPrime(k):
if k%2 == 0:
return "No"
else:
for i in range(3,int(math.sqrt(k))+1,2):
if k % i == 0:
return "No"
return "Yes"
if __name__ == "__main__":
for _ in range(int(input()... |
a84c6789a291df59eb0e20712933bd046b4dded2 | MonkFallsInSnow/OSU-Course-Work | /CS372/project2/ftclient.py | 3,399 | 3.546875 | 4 | '''
Author: Conrad Lewin
Class: CS 372 @ Oregon State University
Date: 3/10/2017
Filename: ftclient.py
Description: The main program file used to run the client process
'''
import sys
import client as c
#constants representing the indices of each argument within argv
HOST = 1
PORT = 2
CMD = 3
DATA_PORT = 4
FILENAME =... |
b8f3498eb35f23f30674489b53b7d82ed1e22fce | MonkFallsInSnow/OSU-Course-Work | /CS325/Project4/vertex.py | 644 | 3.75 | 4 | #defines a vertex object
#id = city id (string).
#cords = tuple of integers representing x and y coordinates
#set = integer id used in Kruskal's algorithm to define sets of vertices
#visited = boolean that indicates whether or not a vertex has been visited
class Vertex:
def __init__(self,name,pos):
self.id = name
... |
bee68707db52f92b3b1716f101ca1a382ef86011 | emilygrobertson/Undergraduate-CIS-Portfolio | /CIS 443/Programs/Program3.py | 2,638 | 3.890625 | 4 | #Grading ID: D3998
#CIS 443-01
#Program 3
#Due Date: Monday November 2, 2020 11:59pm
#This program stimulates a game of craps
import random
games_play=1000000
list_of_wins= {}
list_of_losses= {}
def roll_dice():
die1 = random.randrange(1, 7)
die2 = random.randrange(1, 7)
return (die1, die2) # pack die f... |
231ce28b75879ac60a0827d0ee2f292e112a35cb | KevinXu17/Data-Analysis-with-Python | /Main.py | 5,554 | 3.5625 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
salesDataFrame = pd.read_csv('sales_data.csv', parse_dates=['Date'])
sdf_info = salesDataFrame.info()
print(sdf_info)
graph_size = (20, 8)
# # What's the mean of Customer_Age?
# mean_customers_age = salesDataFrame['Customer_Age'].mean()
# # kde o... |
7898a61e7baff9d7f093d54dfdfb2a0892390b36 | Pagolin/Course_PythonForResearch | /week_three/SciKitClassifier.py | 1,635 | 3.890625 | 4 | """This case study exemplifies classification of 150 irirs flowers into three species based on different size measures
"""
from sklearn import datasets
from sklearn.neighbors import KNeighborsClassifier
import matplotlib.pyplot as plt
import week_three.Classification as my_cl
import numpy as np
#iris is an example ... |
a8e31c69e57ca3ccd34922a2a5a341f2b46699e8 | Pagolin/Course_PythonForResearch | /week_two/Plotting.py | 1,021 | 3.515625 | 4 | import matplotlib.pyplot as plt
import numpy as np
# linspace-> vector of linearly distributed values (first, last, number of values)
# other available distributions e.g. logspace(np.log10(start), np.log10(end), number of values)
x = np.logspace(-1,1,40)
# vector withelementwise squared x-arguments
y1 = x**3
y2 = x**4... |
c77ff57e960b4ddb6979f0d220c42b1c69db0d23 | untitaker/aoc2020 | /day8.py | 1,788 | 3.859375 | 4 | #!/usr/bin/env python
with open("day8.input.txt") as f:
instructions = [line.strip().split() for line in f]
def run():
visited_instructions = set()
acc = 0
i = 0
while i < len(instructions) and i not in visited_instructions:
visited_instructions.add(i)
opcode, argument = instruct... |
d1072a18a4c2758d8c6ea5fc693838d72347ab5a | untitaker/aoc2020 | /day6.py | 540 | 3.671875 | 4 | #!/usr/bin/env python
import string
def run(set_init, func):
answers = set(set_init)
answers_count = 0
with open("day6.input.txt") as f:
for line in list(f) + [""]:
line = line.strip()
if not line:
answers_count += len(answers)
answers = set(... |
744a73d06b9227f34246f7f994d7105e8f5dc1ad | elzbietamal95/Python-tutorial | /Week1/Week1-Problem1.py | 195 | 3.90625 | 4 | s = 'azcbobobegghakl'
total_vowels = 0
for letter in s:
if (letter == 'a' or letter == 'e' or letter == 'i' or letter == 'o' or letter == 'u'):
total_vowels += 1
print(total_vowels) |
964a89b492e5fbf7352c120e5e4258fb5c32eb58 | elzbietamal95/Python-tutorial | /Midterm_Exam/MidExam_Problem6.py | 531 | 4.125 | 4 | def largest_odd_times(L):
""" Assumes L is a non-empty list of ints
Returns the largest element of L that occurs an odd number
of times in L. If no such element exists, returns None """
while len(L) != 0:
maks = max(L)
counter_maks = L.count(maks)
if (counter_maks % 2) !=... |
51af5e9d9d90511e921cdb6ce06c136cc43690f9 | elzbietamal95/Python-tutorial | /Week2/Week2_Problem2.py | 686 | 3.765625 | 4 | def monthlyPayment(balance, annualInteresetRate):
monthlyInterestRate = annualInterestRate / 12
minimumFixedMonthlyPayment = 0
updatedBalance = balance
while updatedBalance >= 0:
minimumFixedMonthlyPayment += 10
updatedBalance = balance
for month in range(1, 13):
mont... |
3ed8cf4ed1879d75d7e09bd008440885d480e61c | nadezhda-sh/python-basics | /6.py | 1,354 | 3.75 | 4 | # Спортсмен занимается ежедневными пробежками.
# В первый день его результат составил a километров.
# Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего.
# Требуется определить номер дня, на который результат спортсмена составит не менее b километров.
# Программа должна принимать значения парам... |
e386030944824cc902c4f7d6363a84fcd763ebce | akhilbharathan/pythonlearner | /palindrome.py | 362 | 4.28125 | 4 | #This code will check whether a given word is a palindrome or not.
def palindrome(x):
x = x.lower()
y = x[::-1]
if x==y:
print("Palindrome!")
else:
print("Not Palindrome")
palindrome(input(""))
#Sethu C A "Start calling youself to be a beginner in learning programming when you... |
b4ee0c9461fd5d19ff0796134ef06214ea85ddc7 | EdinCitaku/Programming-challanges | /277-Interm.-WeightCoins.py | 2,832 | 4.03125 | 4 | def listOfCoins(left,right): #left and right must have the same size
re = []
for i in range(len(left)) :
for char in left[i]:
if char not in re:
re.append(char)
for char in right[i]:
if char not in re:
re.append(char)
return re
f = ope... |
6c2fbb86370485fde90c308e3eda80679757f86c | windowzzhhuu/keyphrase-extraction | /1. Complete dataset - Full texts/centrality_measures.py | 2,790 | 3.5625 | 4 | # G.M. Vazquez-Sanchez - 05/07/2015 - UoE MSc Artificial Intelligence - Dissertation
# This code computes the Degree, Betweenness and Closeness of each NP (noun phrase) in the collection of papers
# It uses the networkx library to compute Degree, Betweenness and Closeness
# The output are documents where NPs are sorted... |
a8f74f520a0b06e8646bae158da6f51149cf3e38 | kaushik853/lpthw_python_3 | /zed-python/singlylinkedlist.py | 1,364 | 4.28125 | 4 | #create node
#create Linkedlist
#add node to Linkedlist
#print Linkedlist
#head is the first linkedlist with data,next as None
class Node:
def __init__(self,data):
self.data = data
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
def insert(self,newNode):
... |
af7cd7f4e11d845d65e6b2080e59350ed28253db | kaushik853/lpthw_python_3 | /zed-python/got.py | 4,740 | 3.9375 | 4 | from sys import exit
from textwrap import dedent
class Scene(object):
print("Nothing is written yet")
def enter(self):
print("I need to write it")
exit(1)
class Start(Scene):
def enter(self):
print(dedent(
"""
You are starting the Game Of Thrones.
... |
9a7e1b1892e017bdeaa0668d6ce1385ef741453c | diazale/advent_of_code_2020 | /advent_of_code_20201204.py | 3,555 | 3.75 | 4 | """
Passport data contains the following fields
byr (Birth Year)
iyr (Issue Year)
eyr (Expiration Year)
hgt (Height)
hcl (Hair Color)
ecl (Eye Color)
pid (Passport ID)
cid (Country ID)
Passports are separated by blank lines
In order to be valid, passports must have all fields (cid is optional)
"""
f = open("input_2... |
756d96f61572f887abf87faba0e8162b77a1a43b | fabioarnoni/python-journey | /ex27_binary_chop_game.py | 736 | 3.859375 | 4 | # Binary Chop Game (High low)
low = 1
high = 1000
guesses = 0
guess = 0
print("Please think of a number between {} and {}: \n".format(low, high))
input("Press Enter: ")
while True:
print("Guessing a number between {} and {}".format(low, high))
guess = low + (high - low) // 2
hi_low = input("My guess is {}... |
e11d26a7683affceedacdada479babdd996b904a | fabioarnoni/python-journey | /ex7_operator_precedence.py | 377 | 3.9375 | 4 | # Operator precedence
a = 12
b = 3
print(a + b)
print(a - b)
print(a * b)
print(a / b) # Result given as float
print(a // b) # Result given as integer
print(a % b) # Division Rest
print()
print(a + b / 3 - 4 * 12)
print(a + (b / 3) - (4 * 12))
print((((a + b) / 3) - 4) * 12)
print(((a + b) / 3 - 4) * 12)
c = a + b
... |
7a7155c60ffae258194c7b92a63d005ae69ef270 | fabioarnoni/python-journey | /ex24_while_loops.py | 447 | 3.765625 | 4 | # While Loops
i = 0
while i < 10:
print("i is now {}".format(i))
i += 1
print("#" *80)
j = 0
End = True
while End == True:
print("j is now {}".format(j))
if j == 10:
End = False
j += 1
print("#" *80)
available_exits = ['north', 'south', 'east', 'west']
chosen_exit = ""
while chosen_exit... |
dacfe181c7ef1d238e4cd3a5dc2e152c9e06c337 | UtkuGlsvn/Python-Data-Structures | /Stack.py | 740 | 3.828125 | 4 | # @Author: utkuglsvn <utkuglsvn>
# @Date: 2019-04-19T13:43:04+03:00
# @Last modified by: utkuglsvn
# @Last modified time: 2019-04-19T14:01:19+03:00
#python stack = list
class Stack:
def __init__(self):
self.stack=list()
def push(self,value):
self.stack.append(value)
def pop(self):
... |
1b20fc369747a1fa82817a7e4d289abf8e39a35c | lxhello/SMS | /student_class.py | 656 | 3.84375 | 4 | class Student:
def __init__(self, stu_id, name, gender, age, major):
self.stu_id = stu_id
self.name = name
self.gender = gender
self.age = age
self.major = major
def display_stu_info(self):
print("-" * 30)
print("stu_id:" + self.stu_id)
print("na... |
e0e8667abea187da14a5f68f630be93b5a406cd4 | DiegoMont/ClubProgramacion | /Codeforces/BinaryDequeue.py | 2,060 | 3.5 | 4 | """ BINARY DEQUEUE
Slavic has an array of length n consisting only of zeroes and ones. In one operation, he removes either the first or the last element of the array.
What is the minimum number of operations Slavic has to perform such that the total sum of the array is equal to s after performing all the operations? In... |
65225f702081d096ab7d44d13147ad9afe09a761 | fparat/adventofcode | /2019/day12/part1.py | 2,449 | 3.5625 | 4 | #!/usr/bin/env python3
# coding: utf-8
import re
import itertools
from dataclasses import dataclass
from typing import NamedTuple
@dataclass
class ThreeDimension:
x: int = 0
y: int = 0
z: int = 0
def abs_sum(self):
return abs(self.x) + abs(self.y) + abs(self.z)
@classmethod
def from... |
32f9d0586ef14edf951bfa247ec8ce35bc8e68ea | fparat/adventofcode | /2019/day12/part2.py | 3,145 | 3.59375 | 4 | #!/usr/bin/env python3
# coding: utf-8
import re
import itertools
import math
from dataclasses import dataclass
from functools import reduce
@dataclass
class ThreeDimension:
x: int = 0
y: int = 0
z: int = 0
def dimension(self, dimension):
return getattr(self, dimension)
def abs_sum(self... |
f6a498bef187474d495f3bbbd9a8a521e5cc1c79 | fparat/adventofcode | /2020/day07/part1.py | 913 | 3.796875 | 4 | #!/usr/bin/env python3
# coding: utf-8
if __name__ == "__main__":
with open("input") as f:
s = f.read()
# Parse
rules = {}
for line in s.splitlines():
container, contained_desc = line.strip(".").split(" bags contain ")
contained = {}
if contained_desc != "no other bags... |
f355b06b757fa38396b259797094b11fc2d9cbb9 | fparat/adventofcode | /2020/day09/part1.py | 484 | 3.796875 | 4 | #!/usr/bin/env python3
# coding: utf-8
import itertools
def find_bad_num(nums, preamble_len):
for i in range(preamble_len, len(nums)):
previous, num = nums[i-preamble_len:i], nums[i]
ok = any((a+b) == num for a, b in itertools.permutations(previous, 2))
if not ok:
return num
... |
0a7dd0bb08acf78b472f3c23f4382272ab8d1c6a | Isterikus/vk_cup | /round1/a.py | 521 | 3.9375 | 4 | from math import sqrt
from itertools import count, islice
def isPrime(n):
if n < 2: return False
for number in islice(count(2), int(sqrt(n) - 1)):
if not n % number:
return False
return True
x2 = int(input())
def primes1(n):
""" Returns a list of primes < n """
sieve = [True] * (n / 2)
for i in range(... |
096641e4a9e2c4bb324a4e76173024bdbb8bfb03 | jwlodek/clanimate | /clanimate/wheelindicator.py | 1,561 | 4.15625 | 4 | """
Class for the simplest implementation of the Indicator class,
a spinning wheel animation.
@author: Jakub Wlodek
"""
# clanimate import + time
from clanimate import indicator
import time
class WheelIndicator(indicator.Indicator):
"""
Class for Wheel indicator - a basic animation that cycles through charac... |
d314aadfd451068d9baa43608a0f591b441806d1 | jgarte/Python | /Chapter 01/polygon.py | 175 | 3.53125 | 4 | def drawPolygon(myTurtle,sideLength,numSides):
turnAngle=360/numSides
for i in range(numSides):
myTurtle.forward(sideLength)
myTurtle.right(turnAngle)
|
060b4c08abaa9ef82f9cd95bacd8019b3dab296b | ABresting/Hackerrank | /Reverse a doubly linked list.py | 562 | 4.15625 | 4 | """
Reverse a doubly linked list
head could be None as well for empty list
Node is defined as
class Node(object):
def __init__(self, data=None, next_node=None, prev_node = None):
self.data = data
self.next = next_node
self.prev = prev_node
return the head node of the updated list
"""
... |
344a4565974362b87cce40872309aae356fcb199 | ABresting/Hackerrank | /Running Time of Algorithms.py | 404 | 3.90625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
def insertionSort(ar):
shift = 0
for i in xrange(1, len(ar)):
temp = ar[i]
j = i
while j > 0 and temp < ar[j-1]:
ar[j] = ar[j-1]
j -= 1
shift += 1
ar[j] = temp
print shif... |
bd41ea0b3530d6134fce5333438254c2509004f8 | ABresting/Hackerrank | /Transpose and Flatten.py | 240 | 3.5 | 4 | import sys,numpy
if sys.version_info[0]>=3: raw_input=input
n,m=map(int,raw_input().split())
num=[]
for _ in range(n):
num.append([int(i) for i in raw_input().split()])
num=numpy.array(num)
print(numpy.transpose(num))
print(num.flatten())
|
887b88d6c0429668ac8c5ccca1e2cb57452dd80c | ABresting/Hackerrank | /Print in Reverse.py | 613 | 4.1875 | 4 | """
Print elements of a linked list in reverse order as standard output
head could be None as well for empty list
Node is defined as
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
"""
def ReversePrint(head):
if head==None:
... |
9b2a9b5907b0abdff2a2d7d2c67d6bb913ccea3f | ABresting/Hackerrank | /Insertion Sort - Part 1.py | 441 | 3.859375 | 4 | #!/bin/python
def insertionSort(ar):
num = ar[-1]
for i in xrange(m-2, -1, -1):
if ar[i] > num:
ar[i+1] = ar[i]
print " ".join(str(j) for j in ar)
else:
ar[i+1] = num
print " ".join(str(j) for j in ar)
return
ar[0] = num
print "... |
ad62c36c7ab3a05f0e676964274fe7f212b0a8fa | ABresting/Hackerrank | /Sort Data.py | 341 | 3.671875 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
i1=raw_input().split(" ")
N=int(i1[0])
M=int(i1[1])
table=[]
for i in xrange(N):
table.append(raw_input().split(" "))
table[i]=map(int, table[i])
k=int(raw_input())
table=sorted(table, key=lambda x: x[k])
for i in xrange(N):
print " ".joi... |
ff412bd8b8829413ad2e163c7f5f46478c2459ca | galalelatfawy/python-date-time | /time-to-unit.py | 462 | 3.59375 | 4 | # Import Modules
import helper
# User Inputs
user_input = ""
while user_input != "exit":
user_input = input("Hey user, enter number of days and conversion unit!\n")
days_and_unit = user_input.split(":")
print(days_and_unit)
days_and_unit_dictionary = {"days": days_and_unit[0], "unit": days_and_unit[1]}
... |
95ec7846b0defe7110061ca8f26ea42731a2b866 | poulomikha/HackerRank- | /Day 2 HackerRank | 284 | 3.8125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
meal_cost = float(input())
tip_percent = int(input())
tax_percent = int(input())
tip = meal_cost * tip_percent/100
tax = meal_cost * tax_percent/100
totalCost = meal_cost + tip + tax
print(round(totalCost))
|
bb7c749a91452e17e5fe1d5b36e610e8162f9d5a | victoriamreese/Code-Academy | /math_functions.py | 901 | 4.09375 | 4 |
# Factorial Function:
def factorial(n):
if n ==:
return 1
else:
return n * factorial(n-1)
# *uses function recursion
def factorial(n):
p = 1
while n > 1:
p *= n
n = n - 1
return p
# Digit summation:
def digit_summed(n):
soonsummed = []
strung = str(n)... |
e77d15e9338f062e115cea4f669a81cd69296cd4 | grizzly-ops/python-crash-corse | /chap06/example 1.py | 237 | 3.734375 | 4 | favorite_numbers = {
'lucy':[21,55],
'jack':[81,91],
'bob':[41,31],
'griz':[9,12],
}
for name, numbers in favorite_numbers.items():
print (f"\n{name.title()}'s favorite numbers are:")
for number in numbers:
print(f"\t{number}")
|
ab4602813541779e4d80f04f4640c1324a029c73 | mfouda/Clustering-Algorithms | /lloyd.py | 1,481 | 3.53125 | 4 | '''
An Implementation of the Lloyd's Algorithm for clustering
usage: python lloyd.py [input_csv_filename.csv]
'''
import csv,pylab
import numpy as np
import pylab
import cluster
from numpy.linalg import norm
import sys
def kMeans(X,k):
# select 10 random initializations and select the best out of them
(yBest, cBest... |
18d37e6efc330f14272c8ccac411fa390e2a1e4e | ivand200/Coursera_Python_for_everybody | /variable_02.py | 774 | 4.28125 | 4 | # Exercise 3: Write a program to prompt the user for hours and rate per hour to
# compute gross pay.
hours = int(input("Enter hours: "))
rate = float(input("Enter rate: "))
pay = hours * rate
print("Pay: ", round(pay, 2))
# Exercise 4: Assume that we execute the following assignment statements:
width = 17
height = ... |
c7fc86726947cdb2b230a9d25b2fe59310950d83 | somemarsupials/noughts-and-crosses | /xo/cli/print_board.py | 994 | 3.59375 | 4 | from textwrap import indent
from xo.state import Board, Piece
def _piece_to_string(piece):
if piece == Piece.CROSS:
return "x"
if piece == Piece.NOUGHT:
return "o"
return " "
def _row_to_string(row):
return " | ".join(map(_piece_to_string, row))
def _board_to_rows(board):
arr... |
c6168b08f012dd696a59d4123d4a48defda99712 | austinrucker12/python2018 | /8 ball.py | 399 | 4.03125 | 4 | name = input("what is your name?")
print(f"hi {name}")
import random
mylist = ["yes","no","dont count on it","most likey not","very much so"]
while True:
n = input("what is your question,and if you want to leave you have to say thank you magic 8 ball")
answer = random.choice(mylist)
print("your answer is ... |
1a25e44ac51732974040ab2be8e302a67423a023 | zhenshan-bing/SnakeVrepPython | /SnakeVrepPythonSynch/2D_representation.py | 2,222 | 4.03125 | 4 | # # Nengo Example: 2-Dimensional Representation
#
# Ensembles of neurons represent information. In Nengo, we represent that information with real-valued vectors -- lists of numbers. In this example, we will represent a two-dimensional vector with a single ensemble of leaky integrate-and-fire neurons.
# ## Step 1: Cre... |
4ca5a4498abca3b0c769aadbe4235bbfa909487f | azmimr/tutorials | /src/pcrash_c4.py | 1,150 | 4.4375 | 4 | # Exercises from Python Crash Course Book
# Chapter 4: Working with Lists
# 4.1 Pizzas
pizzas = ['cheese', 'super', 'singapura']
for pizza in pizzas:
print("I like " + pizza + " pizza.")
print("I really like pizza!")
# 4.2 Same type of exercise as above - skipped
# 4.3 Count to 20
for num in range(1,21):
... |
e3a877e7ec018f49c92e6451487341887cde4e4d | xCiaraG/Advent-Of-Code | /2017/day08_puzzle01.py | 758 | 3.625 | 4 | from sys import stdin
def greater_than(a, b):
return a > b
def less_than(a, b):
return a < b
def greater_than_equal(a, b):
return a >= b
def less_than_equal(a, b):
return a <= b
def equal(a, b):
return a == b
def not_equal(a, b):
return a != b
lines = stdin.readlines()
variables = {}
functions = {"<" : les... |
2ab1dbf9c9a03d363ab9d5c589a9bca039976b3e | lijusheng90/py_utils | /util/datetime_tools.py | 1,303 | 3.6875 | 4 | from datetime import datetime, timedelta
def is_valid_date(string, date_format="%Y-%m-%d"):
try:
datetime.strptime(string, date_format)
except ValueError:
return False
return True
def check_input_datetime_scope(self, expos_date_scope):
if not isinstance(expos_date_scope, list) or len... |
f0196f493cca5b124710482311e72b2c66be9efb | dim-akim/python_lessons | /profile_9/robot.py | 436 | 3.953125 | 4 | price = int(input())
before = 0
i_have_stocks = False
while price: # while price != 0
before = price
price = int(input())
if not i_have_stocks and price > before:
price_min = price
i_have_stocks = not i_have_stocks
elif i_have_stocks and price < before:
price_max = price
... |
93d3c8e1ae7da22e8785f0339c256a078dbf70c8 | dim-akim/python_lessons | /yandex-lyceum/for/Shwatz vs Godzilla.py | 1,575 | 3.9375 | 4 | """
Арнольд Шварценеггер стреляет в ужасного монстра Годзиллу из дробовика.
Нужно найти общую величину урона, нанесённого Годзилле выстрелом.
Подсказка: возможно, для быстрой работы программы вам пригодится алгоритм Евклида.
Формат ввода
Сначала вводится количество дробинок.
Затем урон от каждой дробинки. Урон от каж... |
ddd7548f4bfa97cb22e72df37f59ace880747cef | dim-akim/python_lessons | /test.py | 998 | 3.625 | 4 | def div_count(n, divisor):
count = 0
while n % divisor == 0:
n //= divisor
count += 1
return count
with open('27-B.txt') as file:
n = int(file.readline())
numbers = [int(line) for line in file]
matrix_2_5 = [[0 for i in range(9)] for j in range(9)]
# 2 по горизонтали, 5 по вертик... |
bb8297d9bbde029a494cce6e3c3fc05cd58ef36d | dim-akim/python_lessons | /profile_10/lesson2_sort_new.py | 379 | 3.6875 | 4 | n = 6
a = [2, 8, 15, 6, -5, 3]
b = []
for i in range(n):
# ищем минимальное значение в массиве
minimum = a[0]
for j in range(n):
if a[j] < minimum:
minimum = a[j]
b.append(minimum)
a.remove(minimum)
n = n - 1 # решаем проблему с изменением длины списка
print(b)
|
33807cf8b227aacfa2f4c9407469e1b7deb7f837 | dim-akim/python_lessons | /9base/lesson_animation_1.py | 295 | 3.84375 | 4 | from turtle import *
def create_ball(x, y):
t = Turtle()
t.shape('circle')
t.speed(0)
t.up()
t.goto(x, y)
return t
def move(something):
print('Я подвинуль')
ball = create_ball(-100, 100)
while True: # Бесконечный цикл
move(ball)
|
d625a546736ea3dc9b4902237440227960b59986 | dim-akim/python_lessons | /Stepik/2.6-week/matrix-2.py | 1,222 | 3.53125 | 4 | """
Напишите программу, на вход которой подаётся прямоугольная матрица в виде последовательности строк,
заканчивающихся строкой, содержащей только строку "end" (без кавычек)
Программа должна вывести матрицу того же размера, у которой каждый элемент в позиции i, j
равен сумме элементов первой матрицы на позициях (i-1, ... |
b41981e148fcfc8f03965dccde38d219928ca120 | dim-akim/python_lessons | /10profile/factorize.py | 482 | 3.796875 | 4 | from one_way_algo import is_prime
from one_way_algo import find_simple_numbers
def factorize(n: int):
"""
Выводит на экран все простые делители числа n в строчку
:param n: Целое положительное число
"""
for divisor in range(2, n+1):
if n % divisor == 0 and is_prime(divisor):
pri... |
7216a5f28ccec3eacb0e01e6429e67950005301d | dim-akim/python_lessons | /messenger/step_4/ver_4_getter.py | 1,006 | 3.625 | 4 | """
Получатель сообщений из мессенджера
Отправляет в запросе дополнительный параметр - last_timestamp - метка времени последнего сообщения
Получает только те сообщения, которые пришли позже метки
Сервер должен принять и обработать дополнительный запрос
"""
import requests
import time
from datetime import datetime
l... |
5954366816b962eeca7dcc85a6ae813bf784839f | dim-akim/python_lessons | /algorythms/сократить-дробь.py | 124 | 3.546875 | 4 | b = int(input())
a = int(input())
d = a
c = b
while b != 0:
t = a % b
a = b
b = t
print(c // a)
print(d // a)
|
caa4e25fa65927986a5dcd961be5b6f1f5823492 | skalpanai7/kalpana12 | /name.py | 60 | 3.75 | 4 | num=int(input())
if num%2==0:
print num
else:
print num-1
|
40197e419680a0320736a571b0019a63aaec54bc | skalpanai7/kalpana12 | /kalpana12.py | 109 | 3.90625 | 4 | n=int(input())
if (n<=0):
print("invalid")
if (n>0):
if (n%2==0):
print("Even")
else:
print("Odd")
|
55c0845bf4655c3180d86d1ab5be0abd6ec93c98 | antondelchev/Conditional-Statements---More-Exercises | /04. Transport Price.py | 344 | 3.8125 | 4 | distance_km = int(input())
day_or_night = input()
price = 0
if 20 <= distance_km < 100:
price = 0.09 * distance_km
elif distance_km >= 100:
price = 0.06 * distance_km
elif day_or_night == "day":
price = 0.7 + distance_km * 0.79
elif day_or_night == "night":
price = 0.7 + distance_km * 0.9
... |
70d35d32df7ab7ed5ea064979206704ebc3c8084 | aseastman/MachineVision | /Digits_learning.py | 1,180 | 3.984375 | 4 | #This code uses OpenCV to predict digits using kNN
import numpy as np
import cv2
from matplotlib import pyplot as plt
#Read in the image as grayscale
img = cv2.cvtColor(cv2.imread('digits.png'),cv2.COLOR_BGRA2GRAY)
#Separate each number in the image
cells = np.array([np.hsplit(row,100) for row in np.vsplit(img,50)]... |
18237ce4b88aa284c4e9da35f390c8a032ba492c | starkworld/CodeSignals-Practice | /CircleOfNumbers.py | 523 | 4.21875 | 4 | """
Consider integer numbers from 0 to n - 1 written down along the circle in such a way that the distance between any
two neighbouring numbers is equal (note that 0 and n - 1 are neighbouring, too). Given n and firstNumber,
find the number which is written in the radially opposite position tofirstNumber. Example For n... |
7ef9fec9719fee508239b569acc291a5f08e2a3a | starkworld/CodeSignals-Practice | /slicing and dicing files.py | 12,819 | 3.59375 | 4 | from idlelib.TreeWidget import TreeNode
from math import sin, cos, sqrt, atan2, radians
from typing import List
import requests
"""Account validation code Akuna Capitals"""
inp = input("enter:")
try:
j = int(inp[:-2].upper(), 16)
except:
print("INVALID")
else:
k = int(inp[-2:].upper(), 16)
... |
d71e1a2f08999d3b48885af853c7d58818fcd598 | starkworld/CodeSignals-Practice | /firstDuplicate.py | 526 | 3.640625 | 4 | def firstDuplicate(a):
found = {}
for num in a:
if num in found:
return num
else:
found[num] = 1
return -1
# First non repeating Character
def firstNotRepeatingCharacter(s):
count = {}
for char in s:
if char in count:
count[char] += 1
... |
85585f7064cb5e8dc7ee0ecfe3e5099ec6f7a7a7 | seyoungnam/Language-basics | /Python/chap06_operator_overloading.py | 549 | 3.625 | 4 | # Operator Overloading
# https://blog.hexabrain.net/287
class Num:
def __init__(self, num):
self.num = num
def __add__(self, num):
self.num += num
def __sub__(self, num):
self.num -= num
if __name__ == '__main__':
n=Num(100)
print(n.num) # 100을 출력
n+100
print(n.num)... |
6b71bd75b71ec7556d3664dcef4279516faeef6f | seyoungnam/Language-basics | /Python/chap07_Inheritance.py | 811 | 4.1875 | 4 | class Person: # Base class
def __init__(self, name, age): # 이름과 나이를 입력 받아 초기화
self.name = name
self.age = age
def PersonInfo(self): # 이름과 나이를 출력하는 메소드
return self.name + " : (age :" + str(self.age) + ")"
class Student(Person):
def __init__(self, name, age, grade):
Person.... |
97671e32e9851b8b2afc1cc63930f01b9d09f798 | seyoungnam/Language-basics | /Python/chap07_ex03.py | 620 | 3.703125 | 4 | class My:
def __init__(self):
self.x=0
@property # getter에 해당
def mFun(self):
return self.x
@mFun.setter # setter에 해당
def mFun(self, x):
self.x = x
@classmethod # 상속시 cls인자를 활용하여 자손클래스의 속성을 가져옴
def class_Fun(cls,x):
print("class_Fun(%s%d)"%(cls,x))
@st... |
b92e82f61296609aa0b195042134348bc6ab4b1b | tranduccuong90/C4E21 | /session2/condi_intro.py | 765 | 3.84375 | 4 | # yob = int(input("Your year of birth? "))
# age = 2018 - yob
# print("Your age:", age)
# if age < 10:
# print("Baby")
# elif age < 18:
# print("Teenager")
# else:
# print("Adult")
print("Hay dien cac tham so a, b, c trong phuong trinh bac 2: ax2 + bx + c = 0")
a = float(input("a: "))
b = float... |
5c4c8a87844bd14392398e5833c5f0e6549991f6 | tranduccuong90/C4E21 | /session3/ss3_excercise/ss3_hw3a.py | 526 | 3.9375 | 4 | items = ['T-Shirt', 'Sweater']
while True:
command = input('Welcome to our shop, what do you want? (C, R, U, D) ').upper()
if command == "C":
new_item = input("Enter new item: ")
items.append(new_item)
elif command == "R":
pass
elif command == "U":
pos = int(input("Up... |
068c0515e0e7c95f1cf85b33cef1933fdf827d55 | tranduccuong90/C4E21 | /session1/ss1_excercise/ss1_hw2.py | 68 | 3.84375 | 4 | radius = float(input("Radius ?"))
print("Area = ",3.141592 * radius) |
b97bf015d03cd9f0450b30a3ad7751a5e5e7fe78 | jluissilver/Examen-Final-SaldivarHospinaJimmy-Python | /EjerciciosModulo2/Problema 1 - Mario Game/mario.py | 236 | 4.21875 | 4 | n=int(input("Digite un número entre 1 y 8 : "))
while(n<1 or n>8):
print("Digite un número entero entre 1 y 8 : ")
n=int(input("Digite un número entre 1 y 8 : "))
for i in range(1,n+1,1):
print(" "*(n+1-i)+"#"*i) |
0ee693ca1e32dce4f53addac6d45bb3f50cedf21 | jluissilver/Examen-Final-SaldivarHospinaJimmy-Python | /EjerciciosModulo2/Problemas diversos/Problema1.py | 563 | 4.125 | 4 | def lista_alumnos(num_alumnos):
alumnos=[]
for n in range(num_alumnos):
alumno = {}
alumno['Nombre'] = input('Ingrese el nombre completo : ')
alumno['Nota1'] = float(input('Ingrese nota 1 : '))
alumno['Nota2'] = float(input('Ingrese nota 2 : '))
alumno['N... |
ed7f956cadb67ecd445bb62899c4ba5bd87ffe30 | omarKaushru/Python-Basic | /Basic/main.py | 3,270 | 3.984375 | 4 | # Conditional Statements
"""
a = input()
b = input()
if a > b:
print(a)
print("hi")
elif a == b:
print("equal")
else:
print(b)
print("habi jabi")
print("nothing")
print("egg")
"
# while loop
x = 0
while x < 10:
print(x)
x = x+1
# for loop
for i in range(11, 20):
print(i)
for i in... |
1109b7b03ad6474b25f96a8ff1549875a42a1376 | HeatDeath/SortAlgs | /QuickSort.py | 2,716 | 3.953125 | 4 | '''
排序名称: 快速排序(Quick Sort)(交换排序)
基本思想: 通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,
然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列
性能: 时间复杂度O(nlog2n) 不稳定的排序
'''
import random
import time
def QuickSort(a,lo,hi):
if lo>=hi:#如果只有一个数字时,结束递归
return
flag=lo
for i in range(lo+1,hi+1):#以... |
fdb80af7f13ddb7c5f3689345a9cea28ae127c86 | mosschief/secret_santa | /secret_santa.py | 473 | 3.875 | 4 | from random import shuffle
class person:
def __init__(self, name, email):
self.name = name
self.email = email
self.gift = None
def choose_pairs(people):
shuffle(people)
pairs = []
for i, person in enumerate(people[:-1]):
person.gift = people[i+1]
people[len(people... |
9f2f8c6d9234e1fdbd24a71ea774cecad97ef141 | Winjrk/CP3-Jirakit-Rakwatin | /BMIExample.py | 1,313 | 3.703125 | 4 | import math
from tkinter import *
def leftClickButton(event):
Number = float(textBoxWeight.get())/math.pow(float(textBoxHeight.get())/100,2)
print(Number)
labelResultNumber.configure(text=Number)
if Number >= 30 :
labelResult.configure(text="อ้วนมาก")
elif Number >=25 :
labelResul... |
4fbb74cde9dbf835880110bc616dc3b1463d6bce | koushik1207/Leetcode-Solutions | /Rotate Image.py | 528 | 3.609375 | 4 | class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
l,r = 0,len(matrix) - 1
while l < r:
for i in range(r-l):
t,b = l,r
temp = matrix[t][l+i]
... |
f0b559fbeeda0caa1017626ad02243e755511174 | Akawi85/Stutern_Projects | /sqlite/sql_tasks/task_1/query_test.py | 619 | 3.84375 | 4 | #!/usr/bin/env python3
# import dependencies
import sqlite3
import csv
# create an insurance database
conn = sqlite3.connect("insurance.db")
# create a cursor
cursor = conn.cursor()
# query table values
cursor.execute("SELECT * FROM test_data")
# get five rows from table
items = cursor.fetchmany(5)... |
22b0bd639bc8bdb42503a9cd0068e278ba312079 | Akawi85/Stutern_Projects | /sqlite/sql_tasks/task_2/insurance_app.py | 3,616 | 4.0625 | 4 | #!/usr/bin/env python3
# import dependencies
import sqlite3
# Query the DB and Return all RECORDs
def show_all():
# Connect to database
conn = sqlite3.connect('insurance.db')
# Create a cursor
cursor = conn.cursor()
# select all rows from the test_data table
cursor.e... |
777d9db88ac715954503f718bda672d0ef4b15d5 | story105/Python-Work | /Jairpur_Algorithm.py | 7,626 | 4.125 | 4 | import random
import math
from collections import Counter,OrderedDict
def create_deck():
values = ["Ruby","Gold","Silver","Cloth","Spice","Leather","Camel"]
deck = []
for v in values:
counter = 0
if v == "Ruby" or v == "Gold" or v == "Silver":
amount = 6
elif v == "Cloth" or v ==... |
7b31986ed6b84603fb7d6eb6b61f9df3c62b7c78 | story105/Python-Work | /Recursion.py | 1,361 | 4.09375 | 4 | #I have never played this game before, and this online version is hard as heck
start = []
middle = []
end = []
#This first function just takes the inputted disks and gives the "start peg" list the descending values it needs
def countdisks(disks):
Disk_copy = disks
while Disk_copy > 0:
start.append(Disk_co... |
3f6f71739a1043b1c8d637e694768f5c79b6ef7b | jrmiller82/pathfinder-2-sqlite | /bin/monsters-list-to-files.py | 846 | 3.515625 | 4 | # THIS FILE SIMPLY LOADS THE YAML FILE INTO PYYAML AND THEN SPITS IT BACK OUT
# TO CLEAN UP AND ORDER ALL THE YAML
import yaml
import glob
import os
def main():
# change directory to the data directory
os.chdir('../data/')
# gets all files with a yaml extension in the directory
yfiles = []
for file in g... |
5aa096a47e0f47e746e933a13680bd1986ac688d | aline-paille/BuZzleGame | /src/LettersGenerator.py | 1,765 | 3.578125 | 4 | #!/usr/bin/python3.1
from random import *
from Variables import *
# TODO : variable pour choisir si on prend l'alpha Francais ou anglais
VAR_LANGAGE = "Anglais"
class LettersGenerator:
def __init__(self, language):
self.lettersList = self.lettersHexagon(language)
def couple_probability(self, file):
... |
0f1e167a1dc20867139517ab5413b29b86742dae | bossjoker1/algorithm | /pythonAlgorithm/Practice/hard/6032得到要求路径的最小带权子图.py | 1,182 | 3.5625 | 4 | # 求三个点的最小值
# 枚举两条路中间的交汇点
# 需要建立反图
class Solution:
def minimumWeight(self, n: int, edges: List[List[int]], src1: int, src2: int, dest: int) -> int:
def dijkstra(g:List[List[tuple]], src:int) -> List[int]:
dis = [inf] * n
dis[src] = 0
# 堆优化
q = [(0, src)]
... |
1333ba67d126563436e09e416ed56eee8d82c101 | bossjoker1/algorithm | /pythonAlgorithm/Practice/147对链表进行插入排序.py | 823 | 3.8125 | 4 | # O(n2)
# 维护有序部分的尾节点
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
if not head:
return head
hair = ListNode(0... |
4ef620279fbff22470af55273d30ed5ddf96e170 | bossjoker1/algorithm | /pythonAlgorithm/Practice/427建立四叉树.py | 2,412 | 3.734375 | 4 | # 递归大法好,感觉对于树的递归不是很熟练
"""
# Definition for a QuadTree node.
class Node:
def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):
self.val = val
self.isLeaf = isLeaf
self.topLeft = topLeft
self.topRight = topRight
self.bottomLeft = bottomLeft
self.b... |
28b80fb21d99fc96531c52417e4ca4b720466787 | bossjoker1/algorithm | /pythonAlgorithm/Practice/380O(1)时间插入删除和获取随机元素.py | 777 | 3.53125 | 4 | class RandomizedSet:
def __init__(self):
self.nums = []
self.indices = {}
def insert(self, val: int) -> bool:
if val in self.indices:
return False
self.indices[val] = len(self.nums)
self.nums.append(val)
return True
# 思路是将最后一个元素与被删的元素调换位置
# 然... |
87ddc5831a8abaa9c9d1f18b29812e3f3c1e2a55 | bossjoker1/algorithm | /pythonAlgorithm/Practice/5960将标题首字母大写.py | 445 | 3.5625 | 4 | class Solution:
def capitalizeTitle(self, title: str) -> str:
l = title.split(" ")
res = ""
i = 0
for t in l:
if len(t) == 1 or len(t) == 2:
res += str(t).lower()
else:
temp = str(t)[0].upper() + str(t)[1:].lower()
... |
608f4642317c353c911a3160ebc42fd4861b396c | bossjoker1/algorithm | /pythonAlgorithm/Practice/hard/剑指OfferII114外星文字典.py | 975 | 3.5 | 4 | # 拓扑排序
# 不合法的情况:出现环,前面的长度比后面的还长(后面的是前面的前缀)
# pairwise返回重叠对
# zip(a, b)两两组合成tuple,以短的为准
class Solution:
def alienOrder(self, words: List[str]) -> str:
graph, s = defaultdict(list), set()
for w in words:
s = s.union(set(w))
d = [0] * 26
for a, b in pairwise(words):
... |
2b6715a4cfa4b15196e6830e852ef2d9799c4eac | bossjoker1/algorithm | /pythonAlgorithm/Fundament/test.py | 549 | 3.796875 | 4 | def fib(n):
''' 函数定义'''
a , b = 0, 1
while a < n:
print(a, end=",")
a, b = b, a + b
print
def main():
print('hello world')
b = ['first', 'second', 'third']
for i in b:
print(i, end="") # 不换行
print()
put = int(input("请输入你的数字:"))
print(put)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.