blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
3eefb470c6da99f23213785fba479914399f8728 | Nouw/Programming-class | /les-8/8.1_while-loop_numbers.py | 264 | 3.671875 | 4 | running = True
som = 0
getallen = -1
while running:
getal = int(input("Geef en getal:"))
som += getal
getallen += 1
if getal == 0:
running = False
print("Er zijn " + str(getallen) + " getallen ingevoerd, de som is: " + str(som))
|
d4613de5a15162d087a76da28fd82077cfebc928 | Nouw/Programming-class | /les-11/11.2_json-files_schrijven.py | 961 | 3.609375 | 4 | import json
import os
def store(name, firstl, birthdate, email):
# Basically checks if the data.json file exists if not then create data.json file
files = []
for f_name in os.listdir('.'):
files.append(f_name)
if 'data.json' not in files:
with open('data.json', 'w') as file:
... |
90d57fc0012c7370848d13f914790c03a9f10054 | Nouw/Programming-class | /les-8/ns-kaartautomaat.py | 2,035 | 4.1875 | 4 | stations = ['Schagen', 'Heerhugowaard', 'Alkmaar', 'Castricum', 'Zaandam', 'Amsterdam sloterdijk', 'Amsterdam Centraal', 'Amsterdam Amstel', 'Utrecht Centraal', "'s-Hertogenbosch", 'Eindhoven', 'Weert', 'Roermond', 'Sittard', 'Maastricht']
def inlezen_beginstation(stations):
running = True
while running:
... |
4ab0c17cea4ecc2344962dd34235a0afd3eea132 | Nouw/Programming-class | /les-6/6.5_string_functions.py | 491 | 3.796875 | 4 | # Schrijf functie gemiddelde(), die de gebruiker vraagt om een willekeurige zin in te voeren. De functie berekent vervolgens de gemiddelde lengte van de woorden in de zin en print dit uit.
def gemiddelde(zin):
words = zin.split()
print(words)
totalLength = 0
wordCount = 0
for word in words:
... |
a0d1ec47af81124c47b0c16ea678b230255f2ec7 | Iretiayomide/Week-8 | /Assignment 7b.py | 594 | 3.75 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[9]:
#import libraries
import matplotlib.pyplot as plt
import pandas as pd
#create dataset
names = ['Bob','Jessica','Mary','John','Mel']
status = ['Senior','Freshman','Sophomore','Senior', 'Junior']
grades = [76,95,77,78,99]
GradeList = zip(status,grades)
#create datafram... |
8bf44c4718c44c230b4cac4d0fc5589c0313e31b | lexatnet/school | /python/17-pygame/01-ball/05-collision/engine/collision.py | 2,246 | 3.5 | 4 | def ball_to_box_collision(ball, box):
return {
'x': ball_to_box_collision_x(ball, box),
'y': ball_to_box_collision_y(ball, box)
}
def ball_to_box_collision_x(ball, box):
width = box['size']['width']
height = box['size']['height']
if (ball['rect'].left < 0) or (ball['rect'].right > width):
return... |
f6b956a6dc2d4a44bb586c79f16d541ac2c66cff | matanyehoshua/13.10.21 | /Page 38_8.py | 243 | 4 | 4 | # Page 38_8
x = int(input("Enter a number: "))
y = int(input("Enter another number: "))
# prints the row x times and how many each row y times:
for i in range(x):
for i in range(y):
print ('*', end = ' ')
print()
|
2c8771dfe733ce5d3e7fb1af3105edd36d18534e | JVLJunior/Exercicios-URI---Python | /URI_1153.py | 91 | 3.515625 | 4 | n = int(input())
cont = n
fat = 1
while cont > 0:
fat *= cont
cont -= 1
print(fat)
|
582a8b75d58698a4d89826aecb927d5dd22458d8 | zhuweida/Tracing-Trends-in-Macronutrient-Intake-and-Energy-Balance-Across-Demographics-with-Statistics-and-Ma | /code/pr2.py | 4,428 | 4 | 4 | """
the function of converting RDD into csv file is based on
http://stackoverflow.com/questions/31898964/how-to-write-the-resulting-rdd-to-a-csv-file-in-spark-python/31899173
And some of the initialization code is provided by our instructor Dr. Taufer.
"""
import re
import argparse
import collections
import s... |
820dcba436961e21d6b9b5eb93ad76608904b663 | El-akama/week7_task_oop_encapsulation | /task_oop_incapsulation.py | 2,072 | 3.78125 | 4 | # task1
# class Car:
# def __init__(self, make, model, year, odometer=0, fuel=70):
# self.make = make
# self.model = model
# self.year = year
# self.odometer = odometer
# self.fuel = fuel
# def __add_distance(self, km):
# self.odometer += km
# def __subtrac... |
9264d91dbaf742726eb9c3bf7d70d8931b4556eb | 519984307/BaseHouse | /Python/Base/ProducerConsumer/MultiThread.py | 2,357 | 3.671875 | 4 | import random
import time
from threading import Thread, Lock, Condition
from queue import Queue
class Producer(Thread):
def __init__(self, queue, lock, condition):
super().__init__()
self._queue = queue
self._lock = lock
self._condition = condition
def run(self):
while ... |
1560e2c88d1c43d1d8dce3f9aeee17b1b861bd73 | gracenamucuo/PythonStudy | /ClassAndInstance.py | 3,412 | 4.125 | 4 | class Animal(object):
def run(self):
print('Animal is running')
def run_teice(animal):
animal.run()
animal.run()
#对于Python这样的动态语言来说,不一定需要传入Animal类型,只需要保证传入的对象有一个run()方法就可以。
#判断一个变量是不是某个类型
isinstance(a,Animal)
#判断对象类型,使用type()函数:
#type()函数返回的是Class类型
#判断一个对象是否是函数
import types
de... |
96ecc6d78dea8ae6abfb7123f10867092a0697cd | KatherineCG/TargetOffer | /3-相关题目.py | 974 | 3.84375 | 4 | class Solution:
def SortInsert(self, a1, a2):
if a1 == [] and a2 == []:
return
a1len = len(a1)
a2len = len(a2)
for i2 in range(a2len):
for i1 in range(len(a1)):
if a1[0] > a1[1]:
if a2[i2] >= a1[i1]:
... |
7443a803eb8dbb482fdb44a726b928adeb29a871 | KatherineCG/TargetOffer | /24-二叉搜索树的后序遍历序列.py | 925 | 3.765625 | 4 | #coding=utf-8
#AC笔记:函数返回布尔值
class Solution():
def VerifySquenceOfBST(self, sequence):
length = len(sequence)
if length <= 0 or sequence == None:
return False
root = sequence[len(sequence)-1]
for i in range(0, length):
if sequence[i] > root:
... |
676bc805b36c49dbfb1ecc01daa8b0eb50e63fce | KatherineCG/TargetOffer | /4-替换空格牛客.py | 388 | 3.796875 | 4 | # -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
if not s:
return s
res = ''
for ch in s:
if ch == ' ':
res += '%20'
else:
res += ch
return res
te... |
ed0e02d164d7d65d7a132809961b80845439aed8 | KatherineCG/TargetOffer | /45-圆圈中最后剩下的数字.py | 489 | 3.59375 | 4 | # -*- coding:utf-8 -*-
class Solution:
def LastRemaining_Solution(self, n, m):
# write code here
if n == 0 or m == 0:
return -1
array = [i for i in range(n)]
i = 0
while len(array) > 1:
remainder = (m-1) % len(array)
array = array... |
fb19b66574d2de75d864c3e5b10abd3050346c8d | KatherineCG/TargetOffer | /27-二叉搜索树与双向链表.py | 2,694 | 3.6875 | 4 | # -*- coding:utf-8 -*-
import re
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def Convert(self, pRootOfTree):
# write code here
pLastNodeInList = None
pLastNodeInList = self.ConvertNode(pRootOfTr... |
586de144105ea4e2cd2f0358e08cd6d4eee20714 | KatherineCG/TargetOffer | /29.1-数组中出现超过一半的数字.py | 1,148 | 3.578125 | 4 | # -*- coding:utf-8 -*-
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
# write code here
if self.CheckInvalidArray(numbers):
return 0
number = numbers[0]
times = 1
for i in range(1,len(numbers)):
if numbers[i] == number:
... |
dc06c6c46c4c9c07f2ea7c75cc3a486f1fd4f9fc | KatherineCG/TargetOffer | /3-二维数组的查找.py | 1,681 | 3.96875 | 4 | # coding=utf-8
'''
在一个二维数组中,每一行都按照从左到右递增的顺序排序
每一列都按照从上到下递增的顺序排序。
请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
'''
'''
查找方式从右上角开始查找
如果当前元素大于target, 左移一位继续查找
如果当前元素小于target, 下移一位继续查找
进行了简单的修改, 可以判定输入类型为字符的情况
'''
class Solution:
def Find(self, array, target):
if array == []:
return... |
e8e5aadff96ec0b43260a3f7503e459fbdd88161 | KatherineCG/TargetOffer | /33-把数组排成最小的数.py | 1,104 | 3.703125 | 4 | # -*- coding:utf-8 -*-
class Solution:
def PrintMinNumber(self, numbers):
# write code here
if not numbers:
minnum = ''
else:
length = len(numbers)
numbers = map(str, numbers)
self.Compare(numbers, 0, length-1)
minnum = ''... |
f6c4fb4ad8819c4706d19709aa5955c0221bf3a5 | KatherineCG/TargetOffer | /13-在O(1)时间删除链表结点.py | 1,358 | 3.78125 | 4 | # coding=utf-8
class ListNode:
def __init__(self, data, next = None):
self.data = data
self.next = None
def __del__(self):
self.data = None
self.next = None
class Solution:
def __init__(self):
self.head = None
def DeleteNode(self, pListHead,... |
44869bc89939ee9719d4955b5ba8f24542d9df35 | KatherineCG/TargetOffer | /13-调整数组顺序使奇数位于偶数前面.py | 481 | 3.671875 | 4 | # -*- coding:utf-8 -*-
'''
用两个列表,一个存储奇数,一个存储偶数
返回奇数列表+偶数列表
'''
class Solution:
def reOrderArray(self, array):
# write code here
if not array:
return []
evenres = []
oddres = []
for ch in array:
if ch % 2 == 0:
evenres.appe... |
4f2e3b81459c7de30038d44b7232fea76c621e36 | Z3roTwo/GuessTheNumber | /GuessTheNumber.py | 1,335 | 3.796875 | 4 | import random
import json
loop = True
guess = 0
number = 0
rounds = 0
name = 0
#q = 0
name = input("Display name: ")
number = random.randint(1, 10)
#try:
#with open('Storage.json', 'r') as JSON:
#data = json.load(JSON)
#type(data)
#print(data["name"])
#q = data[rounds]
#except:
... |
dff00f606c61a85f97eadf87e8a939121ed22462 | mananaggarwal2001/The-Perfect-Guess-Game | /project2-the_perfect_guess.py | 999 | 4.03125 | 4 | import os
import random
randInt = random.randint(1, 100)
userGuess = None
Gussess = 0
highScore=None
while(userGuess != randInt):
userGuess = int(input("Enter Your Guess: "))
if(userGuess == randInt):
print("You Guessed it Right")
else:
if userGuess > randInt:
print("... |
25001af33ac7a663e5f20810c42d5cba3ac73242 | AhmedElkhodary/Python-3-Programming-specialization | /1- Python Basics/FinalCourseAssignment/pro5.py | 620 | 4.15625 | 4 | #Provided is a list of data about a store’s inventory where each item
#in the list represents the name of an item, how much is in stock,
#and how much it costs. Print out each item in the list with the same
#formatting, using the .format method (not string concatenation).
#For example, the first print statment shou... |
a53c2faa1c8da8d9f736720d2f653811898ea67a | AhmedElkhodary/Python-3-Programming-specialization | /1- Python Basics/Week4/pro3.py | 256 | 4.3125 | 4 | # For each character in the string already saved in
# the variable str1, add each character to a list called chars.
str1 = "I love python"
# HINT: what's the accumulator? That should go here.
chars = []
for ch in str1:
chars.append(ch)
print(chars)
|
0362c1ae9a526f1ba7b5923d7e28e1d043648556 | ContextLab/quail | /docs/_build/html/_downloads/plot_pnr.py | 515 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
=============================
Plot probability of nth recall
=============================
This example plots the probability of an item being recalled nth given its
list position.
"""
# Code source: Andrew Heusser
# License: MIT
# import
import quail
#load data
egg = quail.load_example... |
a92b0b7e4b40c97f9dcc7aa74f342b4727212f96 | Aakaaaassh/Coding | /Greedy_florist.py | 555 | 3.734375 | 4 | n,x = list(map(int,input().split()))
list1 = []
for i in range(n):
y = int(input("enter price of flower"))
list1.append(y)
print("number of flowers are " + str(n) + " and their prices are ", list1)
Buyer = x
print("Number of buyers are :", Buyer)
res = sorted(list1, reverse=True)
print(res)
def TotalP... |
c3a03b2fda7d388c9626f9a9213d49239e659d67 | Aakaaaassh/Coding | /kth_smallest_element.py | 318 | 3.65625 | 4 | n = int(input("Enter no. of test cases: "))
list2 = []
for i in range(n):
a = int(input("Enter size of array: "))
list1 = list(map(int, input().split()))
k = int(input("Enter kth smallest element: "))
res = sorted(list1)
res = res[k-1]
list2.append(res)
for i in list2:
print(i)
|
fba8df5f519498639cd582e945b592200227eaf6 | IbrahimIrfan/ctci | /1/7.py | 580 | 3.78125 | 4 | # O(M*N) in place
def set0(matrix):
rows = set()
cols = set()
m = len(matrix)
n = len(matrix[0])
#O(M*N)
for r in range(0, m):
for c in range(0, n):
# O(1)
if (matrix[r][c] == 0):
rows.update([r])
cols.update([c])
# O(M*N)
... |
80a40c327baf5f1e7f3e287815d584918410124a | golbeck/PythonExercises | /NeuralNets/MLP pure numpy/NeuralNetV1.py | 9,514 | 3.984375 | 4 | #implements logistic classification
#example: handwriting digit recognition, one vs. all
import numpy as np
import os
####################################################################################
####################################################################################
def grad_cost(bias,theta,X,Y,ep... |
453a816c318a213493b5f6cc9cd9ca2567ae55b9 | golbeck/PythonExercises | /twitter/tweet_parserV1.py | 5,928 | 3.6875 | 4 | import oauth2 as oauth
import urllib2 as urllib
import numpy as np
from pandas import DataFrame, Series
import pandas as pd
import json
# See Assignment 1 instructions or README for how to get these credentials
access_token_key = "89257335-W8LCjQPcTMIpJX9vx41Niqe5ecMtw0tf2m65qsuVn"
access_token_secret = "5tmU9RDxP3tiF... |
57df74cd1011bcce2d372806326c2f61adc6ea14 | naveen-kulkarni0/tensorflow | /flower-classification-tensorflow/data-genr.py | 3,608 | 3.890625 | 4 | """# Data Loading
In order to build our image classifier, we can begin by downloading the flowers dataset. We first need to download the archive version of the dataset and after the download we are storing it to "/tmp/" directory.
After downloading the dataset, we need to extract its contents.
"""
_URL = "https://st... |
5be89cf95fc14294714788db895b2f1ebfc3156b | DiegoCol93/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/9-multiply_by_2.py | 192 | 3.78125 | 4 | #!/usr/bin/python3
def multiply_by_2(a_dictionary):
a_new_dictionary = a_dictionary.copy()
for value in a_dictionary:
a_new_dictionary[value] *= 2
return(a_new_dictionary)
|
a1b182cd04c27dc9c000923a627c7e6cb2a2ff3b | DiegoCol93/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/square.py | 2,275 | 4.25 | 4 | #!/usr/bin/python3
""" Module for storing the Square class. """
from models.rectangle import Rectangle
from collections import OrderedDict
class Square(Rectangle):
""" Por Esta no poner esta documentacion me cague el cuadrado :C """
# __init__ | Private | method |-------------------------------------------|
... |
dec9ef388badcb3f32458c369c96a74e7f132c90 | DiegoCol93/holbertonschool-higher_level_programming | /0x03-python-data_structures/10-divisible_by_2.py | 303 | 3.921875 | 4 | #!/usr/bin/python3
def divisible_by_2(my_list=[]):
if my_list:
list_TF = []
index = 0
for i in my_list:
if i % 2 == 0:
list_TF.append(True)
else:
list_TF.append(False)
index += 1
return list_TF
|
49e4ff54cc9940d752f512059d312e3be381c885 | DiegoCol93/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/1-search_replace.py | 238 | 3.9375 | 4 | #!/usr/bin/python3
def search_replace(my_list, search, replace):
new_list = my_list.copy()
i = 0
while i < len(my_list):
if my_list[i] == search:
new_list[i] = replace
i += 1
return new_list
|
b6474efae6cd4d892f987547912e85c73bb9fb0e | limelier/advent-of-code-2020 | /19/main.py | 2,233 | 3.640625 | 4 | import re
from typing import List
def get_input():
rules = {}
with open('input.txt') as file:
for line in file:
line = line.strip()
if line:
index, contents = line.split(':')
index = int(index)
contents = contents.strip()
... |
b220a0f233abe8c47401f5f91da93abc776434f1 | Jokerzhai/OpenCVPython | /test2/UsingMatplotlib.py | 445 | 3.546875 | 4 | #Matplotlib is a plotting library for Python which gives you wide variety of plotting methods.
# You will see them in coming articles. Here, you will learn how to display image with Matplotlib.
# You can zoom images, save it etc using Matplotlib.
import numpy as np
import cv2
from matplotlib import pyplot as plt
img ... |
e4e7696f0a6eb2eeec5a62723bb85bbcc2fd96b6 | manasakandimalla/ICG-Lab | /Lab_5/transition.py | 337 | 3.9375 | 4 | import matplotlib.pyplot as plt
import math
def translation(x,y,h,k):
plt.plot(x,y,marker = 'o')
plt.plot(x+h,y+k,marker='o')
print "enter the co-ordinates of point :"
x0 = input()
y0 = input()
print "enter the co-ordinates of the new origin :"
h = input()
k = input()
translation(x0,y0,h,k)
plt.axis([-10,10,-10,... |
1c226cd18e417faf1cc865499b4f801b0481f6a2 | nrvanwyck/DS-Unit-3-Sprint-2-SQL-and-Databases | /SC/demo_data.py | 1,207 | 3.859375 | 4 | import sqlite3
conn = sqlite3.connect("demo_data.sqlite3")
curs = conn.cursor()
create_demo_table = """
CREATE TABLE demo (
s TEXT,
x INT,
y INT
);
"""
curs.execute(create_demo_table)
insert_row = """
INSERT INTO demo (s, x, y)
VALUES ('g', 3, 9);"""
curs.execute(insert_row)
... |
3160db69d05f0aed6bbc63f9b2b84020ef4343e0 | CorSar5/Python-World2 | /exercícios 36-71/ex051.py | 209 | 3.765625 | 4 | num = int(input('Primeiro termo: '))
r = int(input('Indique a razão da PA(Progressão Aritmética)'))
décimo = num +(10-1)*r
for c in range(num,décimo,r):
print('{}'.format(c), end='->')
print('ACABOU') |
31a9968211779836bb0e80e1f2c698f69db92b28 | CorSar5/Python-World2 | /exercícios 36-71/ex049.py | 99 | 3.796875 | 4 | t = int(input('Digite um número:'))
for n in range(1,11):
print(f'{n}*{t} é igual a {n * t}') |
7496d32ad90fe4e113b616d72ee8773c9a923897 | CorSar5/Python-World2 | /exercícios 36-71/ex050.py | 274 | 3.796875 | 4 | soma = 0
cont = 0
print('Peço-lhe que me indique 6 números')
for c in range(1, 7):
num = int(input(f'Digite o {c}º valor: '))
if num %2 ==0:
soma += num
cont += 1
print('Deu {} números pares e a soma dos números pares foi {}.'.format(cont,soma)) |
cf09393ec6a76c29cdd9ba6b187edc1121fe612b | CorSar5/Python-World2 | /exercícios 36-71/ex052.py | 220 | 4.15625 | 4 | n = int(input('Escreva um número: '))
if n % 2 == 0 or n % 3 == 0 or n % 5== 0 or n % 7 == 0:
print('Esse número {} não é um número primo'.format(n))
else:
print('O número {} é um número primo'.format(n)) |
a9b43780275bd7e9d95650b80cf984f2619f60ea | SjoerdvanderHeijden/endless-ql | /Jordy_Dennis/QL/expressionnode.py | 8,583 | 4.21875 | 4 | """
An expression can be a single variable, or a combination of a variables with an operator (negation) and multiple other expressions.
All of the types are comparable with boolean operators:
If the variable is 0 or unset, the variable will be converted to a boolean False, True otherwise (just like python does it)
On... |
388da7afc9018562b7670d03135ae6fa5d649aa1 | SjoerdvanderHeijden/endless-ql | /Jordy_Dennis/GUI/form_scroll_frame.py | 2,087 | 3.875 | 4 | """
A scrollframe is basically a modifyable frame with a scrollbar
Each scrollFrame contains a scrollbar, a canvas, and a contentsFrame.
The contentsFrame can contain widgets.
The canvas is only used to attach the scrollbar to the contents frame
"""
from .gui_imports import *
class ScrollFrameGui:
... |
e729e644c6046753e00b30d7d121a6a192054fb6 | merv1618/Python-short-programs | /sample_prime_script.py | 353 | 3.859375 | 4 | from prime_count import primecount
def random_polynomial(x):
return x**2 + 3*x + 1
if __name__ == '__main__':
n = primecount(10)
print("Look at me, I calculated the 10th prime number - it's %i" % n)
print("Now watch me calculate some random polynomial of the 10th prime number")
print("Oh look, ... |
4c374bce6543ab75b8ff194de2eaa543457c6159 | ezalos/Rhinoforcement | /state.py | 7,393 | 3.671875 | 4 | #!/usr/bin/env python
import numpy as np
import copy
from color import *
MAX_ROWS = 6
MAX_COLS = 7
class state():
def __init__(self):
self.init_board = np.zeros([MAX_ROWS, MAX_COLS]).astype(str)
self.init_board[self.init_board == "0.0"] = " "
self.player = "X"
self.board = self.i... |
e63ebf17f9e55783a8c81d4e88cd29870d62c29c | grvn/aoc2018 | /15/day15-1.py | 3,312 | 3.65625 | 4 | #!/usr/bin/env python3
from sys import argv
from heapq import heappop
from heapq import heappush
#########################################
# Denna innehåller problem med hörnfall #
# påverkar ej resultatet av input #
# dessa är fixade i day15-2.py #
# har ej orkat fixa dem här #
############... |
b6d45c2603128eac609cb2199510960df3fbac95 | grvn/aoc2018 | /02/day2-2.py | 437 | 3.53125 | 4 | #!/usr/bin/env python3
from sys import argv
def main():
with open(argv[1]) as f:
input=f.readlines()
id1,id2=next((x,y) for x in input for y in input if sum(1 for a,b in zip(x,y) if a!=b)==1) # Hitta de två rätta ID där endast ett enda tecken diffar
svar="".join(x for x,y in zip(id1,id2) if x==y).strip() # j... |
676a6639f3231701b8c3d53f9a5572bc8948e394 | Daniel-HarrisNL/sprintproject | /graphing/main.py | 9,978 | 3.75 | 4 | ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Homework Helper
This program prompts for an input name of an algebraic function then prompts the user for necessary coefficiencts.
It will compute the graph and ask the user if they wish to disp... |
56351369d6585b08ddc07a36b49e940e08003dae | Omkar-Atugade/Python-Function-Files-and-Dictionaries | /week2.py | 8,680 | 4.1875 | 4 | #1. At the halfway point during the Rio Olympics, the United States had 70 medals, Great Britain had 38 medals, China had 45 medals, Russia had 30 medals, and Germany had 17 medals.
#Create a dictionary assigned to the variable medal_count with the country names as the keys and the number of medals the country had... |
971187848e721a42aec82fb6aa5d13f881d84ff4 | johnmwalters/dsp | /python/q8_parsing.py | 1,242 | 4.40625 | 4 | # The football.csv file contains the results from the English Premier League.
# The colums labeled 'Goals and 'Goals Allowed' contain the total number of
# goals scored for and against each team in that season (so Arsenal scored 79 goals
# against opponents, and had 36 goals scored against them). Write a program to rea... |
e14986cfefedad1430fb1686076503a05adcc7e1 | pavelkasyanov/euler_problems | /src/problem_5/main.py | 345 | 3.75 | 4 | def ifDividesAll(num):
for i in (3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19):
if num % i != 0:
return False
return True
def main():
num = 20
while True:
if ifDividesAll(num):
break
else:
num = num + 10
print(num)
if __name__ =... |
09ebba380e8d5b0fb3681b64d0b9613293f0769b | pavelkasyanov/euler_problems | /src/problem_2/main.py | 474 | 3.8125 | 4 | MAX_FIB_NUMBER = 4 * 1000000
def main():
result_sum = 2
n1 = 1
n2 = 2
while True:
print("=== start iteration ===")
print("n1={}, n2={}".format(n1, n2))
n = n1 + n2
print("n={}".format(n))
if n > MAX_FIB_NUMBER:
print("result sum={}".format(re... |
714808135eb230b3fca687200a112a888a7809fd | dutraph/python_2021 | /basic/while_calc.py | 675 | 4.21875 | 4 | while True:
print()
n1 = input("Enter 1st number: ")
n2 = input("Enter 2nd number: ")
oper = input("Enter the operator: ")
if not n1.isnumeric() or not n2.isnumeric():
print("Enter a valid number...")
continue
n1 = int(n1)
n2 = int(n2)
if oper == '+':
pri... |
fa747700c4617f59a616d2f7cf12d8ad3e85e77f | dutraph/python_2021 | /basic/guess_game.py | 853 | 4.09375 | 4 | secret = 'avocado'
tries = []
chances = 3
while True:
if chances <= 0:
print("You lose")
break
letter = input('Type a letter: ')
if len(letter) > 1:
print('type 1 letter...')
continue
tries.append(letter)
if letter in secret:
print(f'awesome letter {lette... |
c750ed33c5ec4069676685a31f4257f58055d9b0 | nataliaqsoares/Curso-em-Video | /Mundo 01/desafio023 - Separando digitos de um numero.py | 811 | 4.1875 | 4 | """ Desafio 023
Faça um programa que leia um número de 0 a 9999 e mostre na tela um dos dígitos separados.
Ex: Digite um número: 1834
Unidade: 4
Dezena: 3
Centena: 8
Milhar: 1 """
# Solução 1: com está solução só é possível obter o resulatdo esperado quando se coloca as quatro unidades
num = input('Digite um número en... |
c2e3b043f0166381203eeda2ef0305c7f67a9290 | nataliaqsoares/Curso-em-Video | /Mundo 02/desafio064 - Tratando varios valores v1.0.py | 556 | 4.0625 | 4 | """ Desafio 064
Crie um programa que leia vários números inteiros pelo teclado. O programa só vai parar quando o usuário digitar o valor
999, que é a condição de parada. No final, mostre quantos números foram digitados e qual foi a soma entre eles
(desconsiderando o flag) """
num = int(input('Informe um número ou 999 ... |
6282e26c75b7c3673cdbbe6a5418af6232cfa647 | nataliaqsoares/Curso-em-Video | /Mundo 01/desafio035 - Analisando triangulos v1.0.py | 574 | 4.21875 | 4 | """ Desafio 035
Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem ou não formar um triângulo
"""
reta1 = float(input('Informe o valor da primeira reta:'))
reta2 = float(input('Informe o valor da segunda reta:'))
reta3 = float(input('Informe o valor da terceira reta:'))
if (re... |
dd1ae1af46e3a860d227f51cc14f5270e6e4d66d | nataliaqsoares/Curso-em-Video | /Mundo 01/desafio004 - Dissecando uma variavel.py | 718 | 4.25 | 4 | """ Desafio 004
Faça um programa que leia algo pelo teclado e mostre na tela o seu tipo primitivo e todas as informações possíveis
sobre ele """
msg = input(' Digite algo: ')
print('O valor {} e ele é do tipo primitivo desse valor é {}'.format(msg, type(msg)))
print('Esse valor é númerico? {}'.format(msg.isnumeric()))... |
1bc9ada8524c22e186391996992ee6458c992b98 | nataliaqsoares/Curso-em-Video | /Mundo 03/desafio075 - Analise de dados em uma tupla.py | 853 | 4.28125 | 4 | """ Desafio 075
Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre: a) quantas vezes
apareceu o valor 9; b) em que posição foi digitado o primeiro valor 3; c) quais foram os números pares; """
conjunto = (int(input('Informe um número: ')), int(input('Informe um númer... |
0048caeb7b3546c1ae8cc917685d0df5242ad2b3 | nataliaqsoares/Curso-em-Video | /Mundo 01/desafio033 - Maior e menor valores.py | 600 | 4.15625 | 4 | """ Desafio 033
Faça um programa que leia três números e mostre qual é o maior e qual é o menor. """
n1 = int(input('Informe um número: '))
n2 = int(input('Informe mais um número: '))
n3 = int(input('Informe mais um número: '))
maior = 0
menor = 0
if n1 > n2 and n1 > n3:
maior = n1
if n2 > n1 and n2 > n3:
ma... |
474e5fbf97eca5b09a0527b9cf59290b4f4ff08c | nataliaqsoares/Curso-em-Video | /Mundo 02/desafio053 - Detector de palindromo.py | 579 | 3.921875 | 4 | """ Desafio 053
Crie um programa que leia uma frase qualquer e diga se ela é um palíndromo, desconsiderando os espaços.
Ex.: Apos a sopa / A sacada da casa / A torre da derrota / O lobo ama o bolo / Anotaram a data da maratona """
frase = str(input('Informe uma frase: ')).lower().split()
frase = ''.join(frase)
cont_f... |
fccf2bdb5f6afe42e695468b8cefc57fedb19783 | nataliaqsoares/Curso-em-Video | /Mundo 01/desafio028 - Jogo de Adivinhacao v.1.0.py | 526 | 4.25 | 4 | """ Desafio 028
Escreva um programa que faça o computador 'pensar' em um número inteiro entre 0 e 5 e peça para o usuário tentar
descobrir qual foi o número escolhido pelo computador. O programa deverá escrever na tela se o usuário venceu ou perdeu
"""
from random import randint
print('Estou pensando em um número ent... |
693dd4620876b1525d56d4b03c47a34f032feb20 | nataliaqsoares/Curso-em-Video | /Mundo 02/desafio036 - Aprovando emprestimo.py | 842 | 4.1875 | 4 | """ Desafio 036
Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa. O programa vai perguntar o valor da
casa, o salário do comprador e em quantos anos ele vai pagar. Calcule o valor da prestação mensal, sabendo que ela não
pode exceder 30% do salário ou então o empréstimo será negado """
... |
4fdbc344aff48594e6fedfe984943a25854f6aed | nataliaqsoares/Curso-em-Video | /Mundo 01/desafio012 - Calculando desconto.py | 292 | 3.65625 | 4 | """ Desafio 012
Faça um algoritmo que leia o preço de um produto e mostre seu novo preço, com 5% de desconto """
preco = float(input('Informe o preço do produto: '))
novopreco = preco - (preco * 0.05)
print('O produto de preço {} com desconto fica por {:.2f}'.format(preco, novopreco))
|
b32e3fa30f283a656532c6154c7795e319ef6c84 | nataliaqsoares/Curso-em-Video | /Mundo 03/desafio100 - Funcoes para sortear e somar.py | 754 | 4.0625 | 4 | """ Desafio 100
Faça um programa que tenha uma lista chamada números e duas funções chamadas sorteia() e somaPar(). A primeira função
vai sortear 5 números e vai colocá-los dentro da lista e a segunda função vai mostrar a soma entre todos os valores
pares sorteados pela função anterior """
from random import randint
f... |
967aa21504999e6fd116ebd555c548bc26f6903c | nataliaqsoares/Curso-em-Video | /Mundo 01/desafio002.1 - Data de nascimento.py | 514 | 4.125 | 4 | """ Desafio002.1
Crie um programa que leia o dia, o mês e o ano de nascimento de uma pessoa e mostre uma mensagem com a data
formatada (mensagem de saida = Você nasceu no dia x de x de x. Correto?) """
# Solução 1
nasci = input('Quando você nasceu? ')
print('Você nasceu em', nasci, 'Correto?')
# Solução 2
dia = inp... |
acfc2d6ff4b396815192db8f0e87fc8a514fc55d | Guilherme-Avellar/primeiras_aulas | /jogo do ppt aprimorado.py | 1,227 | 4.03125 | 4 | # jogo do pedra, papel ou tesoura, com biblioteca de sorteio
print("Jogo do pedra papel ou tesoura")
player = input("Joque pedra, papel ou tesoura: ")
from random import *
computador = randint(0,2)
if player == "pedra" or player == "Pedra" or player == "PEDRA":
player = 0
else:
if player == "papel... |
a916c4834eeb10336fe9c75e2e58e83684fafac8 | thales-mro/python-cookbook | /3-numbers-dates-hours/15-convert-string-to-datetime.py | 487 | 4.0625 | 4 | from datetime import datetime
#way faster solution than showed in main()
def parse_ymd(s):
year_s, month_s, day_s = s.split('-') # only works if you know the string format
return datetime(int(year_s), int(month_s), int(day_s))
def main():
text = '2020-01-25'
y = datetime.strptime(text, '%Y-%m-%d')
... |
68a32e533997a2817579198a90aafaad911e3fbd | thales-mro/python-cookbook | /2-strings/5-search-and-replace.py | 650 | 3.9375 | 4 | import re
from calendar import month_abbr
def replace_callback(m):
mon_name = month_abbr[int(m.group(2))]
return '{} {} {}'.format(m.group(1), mon_name, m.group(3))
def main():
text = 'yeah, but no, but yeah, but no, but yeah'
print(text.replace('yeah', 'yep'))
text = "Today is 02/01/2020. In... |
499b850f68b05aceb843bcd4f6f94c9cb1077afc | thales-mro/python-cookbook | /2-strings/4-pattern-match-and-search.py | 1,181 | 4.125 | 4 | import re
def date_match(date):
if re.match(r'\d+/\d+/\d+', date):
print('yes')
else:
print('no')
def main():
text = 'yeah, but no, but yeah, but no, but yeah'
print(text.find('no'))
date1 = '02/01/2020'
date2 = '02 Jan, 2020'
date_match(date1)
date_match(date2)
... |
881166784fd6a82253a5b189f956582a7a8de5e0 | firebirdrazer/CodingTests | /check_paren.py | 1,952 | 4.40625 | 4 | def check_bracket(Str):
stack = [] #make a empty check stack
while Str != "": #as long as the input is not empty
tChar = Str[0] #extract the first character as the test character
... |
5794112ddeb0e6706ded784d7fec7249659e9450 | mango915/haliteRL | /Modules/encode.py | 22,954 | 3.84375 | 4 | import numpy as np
def one_to_index(V,L):
"""
Parameters
----------
V: LxL matrix with one entry = 1 and the others = 0
L: linear dimension of the square matrix
Assign increasing integers starting from 0 up to L**2 to an LxL matrix row by row.
Returns
-------
integer corre... |
85e4570b02806f103b50429e1d73ec2652e009fe | iamparul08/Hands-on-P6 | /fileio2_ADID.py | 394 | 3.65625 | 4 | #reading first 11 characters from the file
print("First 11 characters of the file:")
f = open("in1_ADID.txt", "r")
print(f.read(11))
f.close()
#reading first line
print("\nReading first line of the file:")
f = open("in1_ADID.txt", "r")
print(f.readline())
f.close()
#using read() method
print("\nRead ... |
cea334a02a27c95069e54496cc08c6c77eb439e1 | Miranjunaidi/SRMAP_CodingClub_Tests | /Test1/Solutions/Binary/binStrings.py | 568 | 3.625 | 4 |
def all_n_BinStrings(n):
if n == 1:
return ["0", "1"]
else:
given = all_n_BinStrings(n-1)
res = []
for bistr in given:
res.append(bistr + '0')
res.append(bistr + '1')
return res
def numsubString(n, pattern):
return sum([(pattern in s) for s ... |
00b2a919a2f0cb213dfc003e78d64d1957cd5c70 | Lyra2108/AdventOfCode | /2015/Day2/Presents.py | 623 | 3.546875 | 4 | def calculate_package_needs(boxes):
paper = 0
ribbon = 0
for box in boxes:
sizes = list(map(lambda size: int(size), box))
x, y, z = sizes
sizes.remove(max(sizes))
x_small, y_small = sizes
paper += 2*x*y + 2*x*z + 2*y*z + x_small*y_small
ribbon += 2*x_small + 2... |
e6484be2f1f99100731c9fe5043e918fad434070 | Lyra2108/AdventOfCode | /2019/Day1/rocketFuel.py | 926 | 3.75 | 4 | from functools import reduce
def read_in_modules():
input_file = open("input.txt", "r")
return list(map(lambda x: int(x), input_file.readlines()))
def simple_calculate_fuel(modules):
return reduce(lambda x, y: x + y, map(lambda module: calculate_fuel(module), modules))
def calculate_fuel(module):
... |
4789d3e5ea7dae714483f2f25aed18792e2bbfd0 | Lyra2108/AdventOfCode | /2018/Day9/MarbleMania.py | 1,413 | 3.5625 | 4 | from collections import defaultdict
class Marble:
def __init__(self, number):
self.number = number
self.previous = self
self.next = self
def add_next(self, number):
next_marble = Marble(number)
self.next.previous = next_marble
next_marble.next = self.next
... |
8c440e1b948f841260b3befc74c8a9130e5e392a | aalvaradof/X-Serv-Python-Multiplica | /calculadora.py | 735 | 3.796875 | 4 | #!/usr/bin/python3
import sys
from sys import argv
def help():
print('Usage: calculadora.py function op1 op2')
print('Possible functions: sumar restar multiplicar dividir')
N_ARGS = 4
if len(sys.argv) != N_ARGS:
sys.exit("Invalid number of arguments")
func = argv[1]
op1 = argv[2]
op2 = argv[3]
try:
o... |
5306872900fb437bba82f703dc3a39fcfe2d2fc6 | anuj-chourasiya/Data-Sructure-in-C | /Trie.py | 1,373 | 3.875 | 4 |
from collections import defaultdict
class TrieNode:
def __init__(self,data):
self.data=data
self.children=defaultdict(lambda: None)
self.freq=0
self.isTerminal=False
def __str__(self):
return "hey "+(self.data)
class Trie:
def __init__(self,data):
self... |
ac539d583de0ec8897fcd603203f30db94bf7eb9 | sachin3496/PythonCode | /batch10_dec_2018/tic_tac_toe.py | 4,070 | 3.5625 | 4 | from itertools import permutations
import sys
import random
import os
import time
def win(data):
win_comb = [ (1,2,3), (1,4,7), (1,5,9), (2,5,8), (3,6,9), (3,5,7),(4,5,6), (7,8,9) ]
player_comb = list(permutations(sorted(data),3))
for comb in win_comb:
if comb in player_comb :
return... |
010a132e2ef0c05b75d9c72307d09ca94aa21732 | MeiJohnson/compmath | /newton.py | 1,395 | 3.609375 | 4 | import math
def f(arg):
return arg**3 - 2 * arg**2 + 3 * arg - 5
def df(arg):
return 3 * arg**2 - 4 * arg + 3
def ddf(arg):
return 6 * arg - 4
def newton():
a = 1
b = 2
e = 0.000001
cntA = 0
cntB = 0
x = a
xi = x-f(x)/df(x)
cntA += 1
print("a =", a, "b =", b, ... |
53db74810935731d80a071d178185dbe4f7cdd31 | SurajPatil314/Leetcode_Fundamental | /LinkedList/reverseLinkedList.py | 651 | 3.90625 | 4 | """
Reverse a singly linked list.
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
temp = []
temp5 = head
while (head != None):
... |
1312a85c36066029066f2b3d9753b278bc4c4ee3 | SurajPatil314/Leetcode_Fundamental | /LinkedList/checkPalndromeLinkedList.py | 936 | 3.796875 | 4 | """
Given a singly linked list, determine if it is a palindrome.
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
temp2 = head3
temp = []
... |
7bc5e5d8883fef3affe01b8dcfc80ce1845f46a8 | connorjclark/learn-code | /code/roll.py | 373 | 3.75 | 4 | import random
import sys
def roll(min, max):
return random.randint(min, max)
def play_round():
result = roll(1, 6)
print("You got " + str(result))
if result == 6:
print("Nice!")
if result == 1:
print("not good...")
play = True
while play:
play_round()
answer = input("Roll again? y/n: ")
... |
3f4fe3c9790c8839f9d3c32116fa12d1194e0933 | baschte83/os-synchronisation | /LibrarySynchronization.py | 4,776 | 4.0625 | 4 | from sys import argv
from time import sleep
import threading
# semaphore objects
# lock objects for book1 copies
semBook1 = threading.BoundedSemaphore(3)
# lock objects for book2 copies
semBook2 = threading.BoundedSemaphore(2)
# lock objects for book3 copies
semBook3 = threading.BoundedSemaphore(2)
# lock objects ... |
4718c3808d9323e5e39f1c76fa77b0ad5c175ed9 | DivyaraniPhondekar/PythonCode | /date and time.py | 425 | 3.515625 | 4 | import time;
import calendar;
ticks=time.time()
print ("Number of ticks since 12:00am, January 1, 1970:", ticks)
print (time.localtime())
localtime = time.asctime( time.localtime())
print ("Local current time :", localtime)
cal = calendar.month(2016, 2)
print ("Here is the calendar:")
print (cal)
... |
412efbd9c79764a161482cb43adcea5b50d0228d | DivyaraniPhondekar/PythonCode | /list.py | 538 | 3.875 | 4 | squares = []
for x in range(1, 11):
squares.append(x**2)
for x in squares:
print x
list1 = ['physics', 'chemistry', 'maths']
print max(list1) # checks ASCII value
list1.append('history')
print list1
print list1.count('maths')
print list1.index('maths')
list1.insert(2,'computer science')
... |
b245f8a691c067e69b89212cd9bb2fff8ee50128 | curiousTauseef/cryptography-codes | /diffiehellman.py | 1,943 | 3.578125 | 4 | import random
import math
def rabinMiller(num):
# Returns True if num is a prime number.
s = num - 1
t = 0
while s % 2 == 0:
s = s // 2
t += 1
for trials in range(5):
a = random.randrange(2, num - 1)
v = pow(a, s, num)
if v != 1: # this test does not apply ... |
aebe705c785b68173e4eb3ba196dd27297f6348f | Zhangchuchu1234/MH8811-G1902372H | /06/H1.py | 405 | 3.765625 | 4 | from passwordGenerator import genPassword
try:
password_length = int(input("Please input the password length (larger or equal to 4): "))
except:
print("Input error!")
exit()
if password_length < 4:
print("Input length should be larger or equal to 4! ")
exit()
password = genPassword(password_lengt... |
a1ea84b418022f06070c6155f758f9d980b519bb | moisescantero/keepcoding_bc5_reto_binario_entero | /bin_int_tests.py | 1,129 | 3.796875 | 4 | """módulo para hacer tests a módulo bin_int_module.py"""
import unittest#importar para test de pruebas
import bin_int_module#para comprobar funcionalidad
class bin_int_test(unittest.TestCase):
def test_bin_int(self):
self.assertEqual(bin_int_module.convert_bit_int("001"), 1)
self.assertEqual(bin_... |
f76c1e50db88f9f61b22f0a655faf0ff1ed817f7 | ryanhgunn/learning | /unique.py | 382 | 4.21875 | 4 | # A script to determine if characters in a given string are unique.
import sys
string = input("Input a string here: ")
for i in range(0, len(string)):
for j in range(i + 1, len(string)):
if string[i] == string[j]:
print("The characters in the given string are not unique.")
sys.exi... |
1146076cdd44cc42fe31f4b7ae3d4e36c670ffa9 | liramirez/setp01 | /Lab N°1/fibonacci.py | 832 | 4.0625 | 4 |
#~~~~~~~~~~~~~~~~~~~~~~~~~~#
#Nombre : Lizzie Ramirez
#Fecha : 28-Abril-2013
#Actividad : 3 - Fibonacci Lab N°1
#~~~~~~~~~~~~~~~~~~~~~~~~~~#
#~~~~~~~~~~~~~~~~~~~~~~~~~~#
#Declaración de funciones
#~~~~~~~~~~~~~~~~~~~~~~~~~~#
def fibo(n):
if(n==0):
return 0
else:
if (n==1):
... |
44e5468f266e9019b04d4b7e91812dbe87cc5a96 | AlexFSmirnov/Tanks | /py/maze_gen.py | 2,174 | 3.6875 | 4 | from random import randint
class Cell:
def __init__(self, state, right=0, bottom=0, color=0):
self.st = state
self.right = right
self.bottom = bottom
def copyline(prevline):
newline = []
for pc in prevline:
newcell = Cell(pc.st, pc.right, pc.bottom)
newline.appen... |
d279398b290a9f0320bacaa23864b3be614100c3 | AndrewGreen96/Python | /math.py | 1,217 | 4.28125 | 4 | # 4.3 Counting to twenty
# Use a for loop to print the numbers from 1 to 20.
for number in range(1,21):
print(number)
# 4.4 One million
# Make a list from 1 to 1,000,000 and use a for loop to print it
big_list = list(range(1,1000001))
print(big_list)
# 4.5 Summing to one million
# Create a list... |
bc890f0f40a7e9c916628d491e473b5ecfa9bb9b | JanaranjaniPalaniswamy/Safety-Monitoring-in-Restaurants-based-on-IoT | /Source_Code/Restaurant_Environment/simulatedtempiot.py | 1,492 | 3.734375 | 4 | from random import random
import numpy as np
class TemperatureSensor:
sensor_type = "temperature"
unit="celsius"
instance_id="283h62gsj"
#initialisation
def __init__(self, average_temperature, temperature_variation, min_temperature, max_temperature):
self.a... |
00ad5d687e667948ad3a0fa1c785dcce1454c33f | JanaranjaniPalaniswamy/Safety-Monitoring-in-Restaurants-based-on-IoT | /Source_Code/Restaurant_Environment/simulatedweightiot.py | 1,384 | 3.578125 | 4 | from random import random
import numpy as np
class WeightSensor:
sensor_type = "weight"
unit="kg"
instance_id="285h62gsj"
#initialisation
def __init__(self, average_weight, weight_variation, min_weight, max_weight):
self.average_weight = average_weight
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.