blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
c088a97fc8f3caca02ff798ec1bcb7051ff6fbdb | RationalAsh/wheelie_stuff | /scripts/plottest.py~ | 575 | 3.75 | 4 | #!/usr/bin/python
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
#Set up figure, acis and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0,2), ylim=(-2,2))
line, = ax.plot([], [], lw=2)
def init():
line.set_data([], [])
return line
def a... |
7103bdfea4e998836079e36898d2bd117792eaf2 | greenmonn/daily-coding | /python/kick_start_google/number_munchers.py | 731 | 3.609375 | 4 | import pytest
import itertools
def is_in_ascending_order(number):
digits = str(number)
prev = -1
for d in digits:
if int(d) <= prev:
return False
prev = int(d)
return True
def test_ascending():
assert is_in_ascending_order(1456) == True
assert is_in_ascending... |
e38a3ad2253ba9297715b7b3fcb3250e48740923 | alexbprr/CsmallCompiler | /PythonFiles/pythoncode_teste_while2.py | 110 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
x = 1
y = 5
while y>1:
y = y-1
print(str(y))
print(str(x))
|
836fb16617a5ea48485f622118699725d83eef66 | minhdvo/datacamp | /Statistical Thinking in Python - Part 2/bootstrap.py | 4,176 | 3.5 | 4 | # generate bootstrap function
def bootstrap_replicate_1d(data, func):
"""Generate bootstrap replicate of 1D data."""
bs_sample = np.random.choice(data, len(data))
return func(bs_sample)
# short version
#def bootstrap_replicate_1d(data, func):
# return func(np.random.choice(data, size=len(data)))
# gene... |
e4f097e1ec79766ecbf0fece7b02a8b7a381b88a | MrH233/examples-of-Thread-and-Process | /fibonaci_example.py | 1,651 | 4.09375 | 4 | """five ways to give fibonaci list"""
# 1.iterator
class Fibo:
def __init__(self):
self.count = 0
self.num_pre = 1
self.num_aft = 1
def __iter__(self):
return self
def __next__(self):
if self.count == 1:
internal = self.num_aft
self.num_aft... |
442b6d70efaa203024eb4cc6832e9e7d20d7d6ef | citrok25/Codewars-1 | /Solutions/beta/beta_is_it_an_isogram.py | 353 | 3.734375 | 4 | import re
from collections import Counter
def is_isogram(word):
if not isinstance(word, str) or word == '': return False
word = {j for i,j in Counter(
re.sub('[^a-z]', '', word.lower())
).most_common()
... |
911c2affbcea4242b559f8f573b53eeb9f87caee | Rochakdh/python-assignemnt-3 | /7.interpolationsearch.py | 577 | 3.84375 | 4 | def interpolation_search(arr, x):
lo = 0
n = len(arr)
hi = (n - 1)
while lo <= hi and x >= arr[lo] and x <= arr[hi]:
if lo == hi:
if arr[lo] == x:
return True;
return False;
pos = lo + int(((float(hi - lo) / ( arr[hi] - arr[lo])) * ( x - ... |
416a2cfd1540072b670829749518ada209588342 | Sem8/Data-Structures | /heap/max_heap.py | 1,565 | 3.75 | 4 | class Heap:
def __init__(self):
self.storage = []
def insert(self, value):
self.storage.append(value)
self._bubble_up(len(self.storage) - 1)
def delete(self):
if len(self.storage) >= 2:
self.storage[0], self.storage[(len(self.storage) - 1)] = self.storage[(len(self.storage) - 1)], sel... |
891be440469d5ea49efe95c7cc301c19984492a6 | akyare/Python-Students-IoT | /1-python-basics/3-functions/ArgsArguments.py | 949 | 4.59375 | 5 | # Makes sense:
msg_sum = "The sum is:"
# Lets define a function:
def multiply(a, b):
return a * b
# So far so good, lets call it:
multiply(2, 5)
# But what if we want to give a variable amount of arguments
# So lets define a new function, we use an astrix as a way of saying
# multiple arguments are allowed... |
b82ffb025cb40cc9349b2a68254d3f12f05f3ad0 | sachasi/W3Schools-Python-Exercises | /src/03_Variables/01_strings.py | 373 | 3.984375 | 4 | # Instructions: Create a variable named carname and assign the value Volvo to it.
# Solution:
carname = "Volvo"
'''
What I'm doing here is starting the string variable "carname" and assigning it the string value "Volvo" with the "=".
Read more here: https://www.w3schools.com/python/python_variables.asp and https://ww... |
5465baf5b8459f9aed3a9ef1679f7da47c4582e1 | machariamarigi/bootcamp_fourth_day | /Binary_Search/binary_search.py | 2,244 | 4.0625 | 4 | class BinarySearch(list):
"""
This class inherits from the list class.
The __init__() takes two integers as parameters
The first is is the length of the list.
The second is the difference between the consecutive values.
It initializes an instance variable 'length'
It ... |
2a040ae9d37c9dec271c2cb14ff437caa02caaf0 | expertrao08/python-challenge | /PyPoll/pyPollScript.py | 2,598 | 3.703125 | 4 | #Declaring the import os, CSV, operator, collection with counter
import os
import csv
import operator
from collections import Counter
#Define PyPoll_result function
def Pypoll_result():
count = 0
#Looping listdir of raw_data of cvs file
for fname in os.listdir('raw_data'):
print(fname)
coun... |
3be4e946bf90ee20687ca4b73dcaa03b733b00b8 | Nod17/IFRN_Python | /atv11.py | 395 | 4.15625 | 4 |
n1 = int(input("Insira um numero inteiro: "))
n2 = int(input("Insira um numero inteiro: "))
n3 = float(input("Insira um numero real: "))
x = (2*n1)*(n2/2)
y = (3*n1)+n3
z = n3**2
print ("O produto do dobro do primeiro com metade do segundo: {:.2f}" .format(x))
print ("A soma do triplo do primeiro com o terceiro: {... |
06be1fd820481848a740d691d0a5180920f8c416 | Leek03/dsia | /Frank/module 1 game.py | 1,853 | 3.90625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 3 14:46:37 2019
@author: frankhu
"""
import random
#fundamental setting of the program
List=[["0","1","2","3","4"],["-","-","-","-","-"],["o","o","o","o","o"],["o","o","o","o","o"],["o","o","o","o","o"],["o","o","o","o","o"],["o","o","o","o","o"]]... |
e5aca62c67f84ec98f77c686010e4dfaf0fa6729 | vnakcyp/DataStructures | /sort_k.py | 871 | 3.671875 | 4 | import heapq as hq
from heapq import heapify
# def heapSort(arr):
# l = len(arr)
# for i in range(l):
# arr[0] , arr[l-1] = arr[l-1] , arr[0]
# heapify(arr)
# return arr
arr = [2,3,4,5,4,1,8]
heapify(arr)
print(arr)
# arr[0] , arr[len(arr) -1] = arr[len(arr)-1] , arr[0]
l = len(arr)
# ... |
d9cc703cba5b48a8bfe0791f3703b58e3c4b7289 | vwordsworth/advent-of-code | /solutions/2018/day5/solution.py | 1,596 | 3.90625 | 4 | import re
from string import ascii_lowercase
def main():
polymer = read_input()
result = remove_reactions(polymer)
print("Part 1:\n\tLength of resulting polymer: {0}".format(str(len(result))))
result = produce_shortest_possible_polymer(polymer)
print("Part 2:\n\tLength of shortest possible polymer... |
c0ff3299be4eef54f8b1db616f2bc9fb46fb2690 | bruckhaus/challenges | /python_challenges/project_euler/p012_highly_divisible.py | 2,097 | 3.578125 | 4 | __author__ = 'tilmannbruckhaus'
import numpy
import sys
class HighlyDivisible:
# Highly divisible triangular number
# Problem 12
# The sequence of triangle numbers is generated by adding the natural numbers.
# So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.
# The first ten te... |
1db696ebd43ac33788e1d487e956a1f3b6829ccd | andrewkigara/hangmanGame | /hangman.py | 1,904 | 4.25 | 4 | # Daily Python Practise
# Hangman Game, inspired by a tutorial from Kylie Ying
# Her link ^ (https://www.youtube.com/channel/UCKMjvg6fB6WS5WrPtbV4F5g)
import random
from words_file import words
import string
def validate_word(words):
word = random.choice(words) # Chooses a random word in the list
while '-... |
ff818bc81def7fd008bf083c2900d6104aa9ca8f | MichaelMcAleer/CollegeWork | /Decision Analytics/Constraing Programming/Solution/task-1.py | 12,602 | 3.640625 | 4 | """
Decision Analytics - Assignment 1
Task 1 - Logic Puzzle
Michael McAleer - R00143621
A - Identify the objects for the constraint satisfaction model.
The objects for the model are the people involved:
- Carol
- Elisa
- Oliver
- Lucas
B - Identify the attributes for the constraint satisfaction model.... |
bef56bc81badc1c86c66f02fa27c68ebd0c079cc | Onlybsen/MyTestGitHub | /fibonacci.py | 547 | 4 | 4 | def fib(n): #fibonacci series using while loop
f = 0
i = 1
nextf = 0
while n >= 1
print ("Fibonacci no.", f)
nextf = f + i
f = i
i = nextf
n -= 1
def fib1(n): #fibonacci series using for loop with additional checks
f = 0
i = 1
nextf = 1
if n <= 0:
print('Positive non-zero value needed')
els... |
f23914f6e66f9697d4369f220b77d4aa3f65c214 | KristofferFJ/PE | /problems/unsolved_problems/test_437_fibonacci_primitive_roots.py | 455 | 3.90625 | 4 | import unittest
"""
Fibonacci primitive roots
When we calculate 8n modulo 11 for n=0 to 9 we get: 1, 8, 9, 6, 4, 10, 3, 2, 5, 7.
As we see all possible values from 1 to 10 occur. So 8 is a primitive root of 11.
But there is more:
If we take a closer look we see:
1+8=9
8+9=17≡6 mod 11
9+6=15≡4 mod 11
6+4=10
4+10=14≡3... |
24fb5e9379f8ebd9c74ae15b1515c99420049767 | mkebrahimpour/DataStructures_Python | /GeeksForGeeks/Binary Trees/postprder_from_inorder&preorder.py | 808 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 18 20:44:47 2019
@author: sbk
"""
def printpostorder(inorder, preorder, n):
if preorder[0] in inorder:
root = inorder.index(preorder[0])
if root != 0: # left subtree exists
printpostorder(inorder[:root],
... |
18d6d12cd178780ab2669743bbceeca9bf2fddc8 | 1goryan/Practice_rep | /JSON.py | 2,800 | 3.953125 | 4 | """#Работа с JSON
import json #импорт модуля json
nums = [4, 76, 2, 67, 23, 7, 78, 98] #создан список для примера
#записываем в файл
file_name = "E:\Pyth0n\python\modules\\nums.json" # в переменную положим файл с именем nums.json
with open(file_name, 'w') as f:
json.dump(nums, f) #используется для сохранени... |
314f3e5dad0808d3493ce071973f1edf312f9411 | iampkuhz/OnlineJudge_cpp | /leetcode/python/203-remove-linked-list-elements.py | 877 | 3.96875 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# ... |
ecf7a35f715cbb59b8ed27f70f7e83518758aa45 | sssfasih/GPA-Calculator | /gpa calculator.py | 5,599 | 3.640625 | 4 | # Designed By Syed Fasih Uddin
print(f" GPA CALCULATOR")
print(f" Designed By Syed Fasih Uddin \n ")
class Subject():
def __init__(self, name, credit):
self.name = name
self.credit = credit
# print("Name Assigned:", self.name)
# Calculation of GP During S... |
572f5060d1aa66b4c273136ef6a2e0158796a4a0 | aprosk/Algorithms | /Python/recursive_change_combinations.py | 1,175 | 3.703125 | 4 | # returns unique combinations of change for a given value (in cents)
def changeComb(val):
cents = {
'Q':25,
'D':10,
'N':5,
'P':1
}
results = []
def helper(comb):
# calculate remainder
s = 0
for c in comb:
s += cents[c]
... |
57004c00c6fb1a1809fdb723f408f6c2213420aa | Palaniappan-AR/Lambda-function | /Lambda.py | 457 | 3.71875 | 4 | a=[1,2,3,4,5,6,7,8,9,10]
b=lambda x:x*3
c=map(b,a)
print('Output 1:',list(c))
x=lambda x:x**2
print('Output 2:')
for i in range(1,11):
print(x(i))
y=[1,2,3,4,5,6,7,8,9,10]
print('Output 3:',list(map(lambda x:x%2!=0,y)))
'''Output of above program:
Output 1: [3, 6, 9, 12, 15, 18, 21, 24, 27, 3... |
e491f0183ac88e71e4a0615c6cbdd69664db1ad5 | jsoto3000/js_udacity_Intro_to_Python | /tiles.py | 204 | 3.609375 | 4 | # Fill this in with an expression that calculates how many tiles are needed.
print(9*7 + 5*7)
# Fill this in with an expression that calculates how many tiles will be left over.
print(17*6 - (9*7 + 5*7)) |
ffed98cf90136a2dded5ca443ef9695d209a0e49 | thomasjiangcy/tic-tac-toe | /tic_tac_toe.py | 7,630 | 4.09375 | 4 | """
Tic tac toe game implemented in Python 3.x
"""
import sys
class Game:
def __init__(self, n, player1, player2):
self.row = n
self.column = n
self.total_squares = self.row * self.column
self.player1 = player1
self.player2 = player2
self.ICONS = {
s... |
52dd0c378258cb02bb80cb0eff847dd716c2cb02 | davidhemp/advent2016 | /day20_IP_ranges/python/part2.py | 755 | 3.53125 | 4 | def find_allowed(blist, max_value=2**32-1):
minimum = blist[0][0]
maximum = blist[0][1]
included = 0
for ip_range in blist[1:]:
if ip_range[0] <= maximum+1 and ip_range[1] > maximum:
maximum = ip_range[1]
elif ip_range[0] > maximum:
minimum = ip_range[0]
... |
be7cc03c9a7801b2eede72c2378d4b8937296511 | Aslem1/univ | /Python/syntaxe_for.py | 374 | 3.640625 | 4 | for x in range (1,6):
print (x, end = ' ')
print ("\n" *2 + "*" * 15 + "\n")
a= int (input ("a ? "))
b = int (input ("b ?"))
produit_ab = 0
if b < a:
for n in range (0 , b):
produit_ab = produit_ab + a
else:
for n in range (0 , a):
produit_ab = produit_ab + a
assert (produit_ab == ... |
722221e69f0ac8822cbee8a5a9ba225c9b50e297 | shawsey/base64conv | /base64encoder.py | 3,720 | 4.03125 | 4 | #Base 64 Encoder
#Written in Python
import string
#Step 1) ASCII --> DEC --> 8-BIT Binary
#collect plaintext, for letter in plaintext run through asciideclist until a match is found.
#take match, jump one in index, will be equiv decimal of letter
#bin(i) to print the binary value of a decimal
def base64conv(pl... |
2509c32b1f813c944919390865d8f11ea91696fc | AlexeyZavar/informatics_solutions | /15 раздел/Задача I.py | 502 | 3.75 | 4 |
# В файле могут быть записаны десятичные цифры и все, что угодно. Числом назовем последовательность цифр, идущих подряд (т.е. число всегда неотрицательно).
#
import re
counter = 0
# try:
file = open('input.txt', 'r')
temp = re.findall(r"[0-9]+", ' '.join(file.readlines()))
for i in range(len(temp)):
counter += i... |
168d0f3fa5b47f8b2e538b0b16332b7dfdbe89f1 | rexosorous/twitch-bot | /games.py | 5,083 | 3.90625 | 4 | # python standard libraries
import random
# local modules
from errors import *
import utilities as util
class MysteryBox:
"""A game in which users can bid on a box whose contents are a mystery.
The box can contain points, income, or luck.
Parameters
------------
bot : TwitchPy.... |
6b58508498d125706e24c3be06c42cb1123f40b4 | bberzhou/LearningPython | /1PythonFundamentals/dictAndSet.py | 4,152 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度
d = {'michael': 97, 'Bob': 90, 'Tracy': 86}
print(d['michael']) # 97
# 把数据放入dict的方法,除了初始化时指定外,还可以通过key放入
d['Adam'] = 78
print(d['Adam']) # 78
# 一个key只能对应一个value,所以,多次对一个key放入value,后面的值会... |
4f492d59abddb180ec999e9a3e140a2bd6764e7d | sehammuqil/python- | /day59.py | 680 | 3.796875 | 4 | import re
str = "the rain in spain"
x = re.sub("\s","9",str)
print(x)
#________________________
import re
str = "the rain in spain"
x = re.sub("\s","9",str,2)
print(x)
#___________________
import re
str = "the rain in spain"
x = re.search("ai",str)
print(x)
#__________________________
... |
1be4a00f4cf66387c56077e86fa37155db758eae | RafaelL1ma/Exercicios-AquiEduca | /Exercicio prático - 24.09.21/ex1.py | 237 | 4.03125 | 4 | age = int(input("Informe sua idade: "))
if age >= 16 and age < 18:
print("Voto opcional!")
elif age >= 18 and age <= 70:
print("Voto obrigatório!")
elif age > 70:
print("Voto opcional!")
else:
print("Voto inválido!")
|
b5300f0de1c89c93fd0821b08b565cd04f641893 | K1uV/-4- | /lekziya4_task2.py | 188 | 3.875 | 4 | name = input("Input name = ")
age = int(input("input your age = "))
print(f" {name} поздравляю тебя с днём рождения , сегодня тебе {age + 1}") |
49d36a4c67119e0980fa0feef205f5a763368b84 | LaBravel/Tedu-code | /python_base/weekly_test03/1.py | 766 | 3.59375 | 4 | def average(dict) :
L = [i for i in dict.values()]
x = sum(L) / len(L)
print('平均值=',x)
def sorted_down(dict) :
L = ['%s%d分' % (i,dict[i])
for i in sorted(dict,key = lambda x : dict[x],reverse = True)
]
print('成绩从高到低排序为:',L)
def index_max(dict) :
L = ['%s%d分' % (i,dict[i])
... |
368ab540ee1bb797db7e7449776dbfa19fc131e8 | millersteventyler/robots_vs_dinosaurs | /battlefield.py | 2,326 | 3.84375 | 4 | from fleet import Fleet
from herd import Herd
class Battlefield:
def __init__(self):
self.fleet = Fleet()
self.herd = Herd()
def run_game(self):
self.display_welcome()
self.battle()
self.display_winners()
def display_welcome(self):
print('Welcome to Robots... |
4d84167e669a4417bbc6c91285fbbce89176641c | AndreyLizen/Python_Algos | /Урок 1. Практическое задание/task_8.py | 1,625 | 3.5625 | 4 | """
Задание 8. Определить, является ли год, который ввел пользователем,
високосным или не високосным.
Подсказка:
Год является високосным в двух случаях: либо он кратен 4,
но при этом не кратен 100, либо кратен 400.
Попробуйте решить задачу двумя способами:
1. Обычное ветвление
2. Тернарный оператор
П.С. - Тернарные ... |
747c39ba1ac1463f13dfada458576b3c30f8de5f | justinminsk/Python_Files | /Intro_To_Python/Lec17/sort_then_find3.py | 533 | 3.859375 | 4 | whalecounts = [809, 834, 477, 478, 307, 122, 96, 102, 324, 476]
def find_two_smallest(L):
""" (see before) """
# Get a sorted copy of the list so that the two smallest items are at the
# front
temp_list= sorted(L)
smallest = temp_list[0]
next_smallest= temp_list[1]
# Find their indices in ... |
b76371d372144fe05c71bf0b6323bb8521a2796d | mfalcirolli1/Python-Exercicios | /ex54.py | 452 | 3.953125 | 4 | # Grupo de Maioridade
from datetime import date
anoatual = date.today().year
cmaior = 0
cmenor = 0
for c in range(1, 8, 1):
ano = int(input('Em que ano a {}ª pessoa nasceu? '.format(c)))
idade = anoatual - ano
if idade >= 18:
cmaior += 1
elif idade < 18:
cmenor += 1
print('A... |
04b4ae97c87282e6af24c034dcd4245044d8c96b | joyzo14/advent_of_code_2020 | /day1b_2020.py | 522 | 3.953125 | 4 |
def solve(input):
for line in input.splitlines():
for line2 in input.splitlines():
for line3 in input.splitlines():
#if sum is 2020, then print multiplication of this 3 numbers
if((int(line) + int(line2) + int(line3)) == 2020):
print(int(line)... |
f1f6c9396caed8b42692d06452d89cef3cc84fe8 | phelipegm/ai-undergraduate-thesis-project | /datacamp-introduction-to-nlp/SimpleTopicIdentification2.py | 3,104 | 3.546875 | 4 | import warnings
warnings.filterwarnings(action='ignore', category=UserWarning, module='gensim')
from gensim.corpora.dictionary import Dictionary
from nltk.tokenize import word_tokenize
from gensim.models.tfidfmodel import TfidfModel
#Creating a Gensim Dictionary
my_documents = ['The movie was about a spaceshi... |
2c5fb3b1dff7432688a0d5fb26fe006819278c15 | alex-me/nencog | /alex/my_cifar/scnn_cifar.py | 12,756 | 3.609375 | 4 | """
A simple convolutional architecture for a classifer on a subset of CIFAR-100
The personalized classes, and the directory with the personalized datasets are
imported from select_cifar, the script that generates the CIFAR-100 selection
the network architecture is defined using TensorFlow slim
Examples of usage:
# ... |
c75c04f304b10e87a00da1c6e300aa826e7b4543 | davidbuffkin/chessengine | /engine.py | 4,737 | 3.90625 | 4 | #David Buffkin
import chess
import math
from random import random, shuffle
# Print iterations progress
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
"""
Call in a loop to create terminal progress bar
@params:
iteration ... |
a0db952d84d73c42ad9cff130cdbab8762da58ae | malekelthomas/DataStructs_Algo | /stackBalancedParen.py | 949 | 4.1875 | 4 | """
Use a stack to check whether or not a string has a balanced set of parantheses
Balanced = ({[]})
Not balanced = {]
"""
from stack import Stack
def isParenBalanced(parenString):
s = Stack()
index = 0
is_balanced = True
parenDict = {"(" : ")", "{" : "}", "[" : "]"}
while is_balanced and index < len(pare... |
05dfd13124dc304c844257f545849a190b358de9 | Qinusty/Telnet-Game-Server | /Games/HigherLower.py | 5,418 | 3.796875 | 4 | from Games.Game import Game
import random
class HigherLower(Game):
def __init__(self): #Define variables to act as global.
self.mode = None
self.lastnum = 0
self.nextnum = 0
self.score = 0
self.name = 'higherorlower'
self.msg_HighorLow = "Will the nex... |
60c89f4d171cdac7db9d3c0fdd7dad007f32a827 | xxcocoymlxx/Study-Notes | /CSC148/test1 review/past test1/summer2016/depth.py | 544 | 3.96875 | 4 | def max_depth(lst):
'''(list, possibly with nesting) -> int
Return the maximum depth of any element in lst.
lst may be nested arbitrarily.
>>> max_depth([10, 20, [30, [[40]]]])
4
>>> max_depth([])
0
>>> max_depth([[], 10])
1
'''
maximum = 0
for element in lst:
if isins... |
e1e4c79b10233e684487c83ef65dfce04c613021 | Adrianozk/exercicios_python | /resolucoes/ex100.py | 536 | 3.640625 | 4 | from random import randint
from time import sleep
def sorteia():
print('Sorteando 5 valores da lista: ', end='')
for i in range(0, 5):
numero = randint(1, 10)
print(f'{numero} ', end='')
numeros.append(numero)
sleep(0.4)
print('PRONTO!')
def somaPar():
print(f'... |
c73cf3480a2ab10b9f3b70487a9a35c7349e0fd6 | Jack-Pincombe/PythonPen | /passwordHash.py | 221 | 4 | 4 | '''
A function that will hash a password it is given
'''
import crypt
def hash(word):
print("Your hash is --> " + crypt.crypt(word,'HIX'))
if __name__ == '__main__':
hash(input('Enter you chosen password -->')) |
00a1a8717d40e90ef0480723acb3519f6ce4c1c3 | LeeDonovan/Code | /EE_381/Lab3/Lab3_Part2.py | 3,451 | 3.65625 | 4 | import numpy as np
import matplotlib.pyplot as plt
n = 100000
counter = 0
points = 3
pie = 2*np.pi
half = 180
checker = 0
np.random.seed()
inside = False
for i in range(n):
opposites = []
theta = np.random.uniform(0,360,3)
radius = 3#np.random.uniform(0, 5, points) ** 0.5
x = radius * np.cos(thet... |
fe9b6b25d0b268c3b1d1c2f439263aa7391625b8 | jldazai/ejemplos-Python | /ejercicio4.py | 653 | 3.875 | 4 | #ejercicios con codicionales .21
dia = int(input("ingrese el numero del dia correspondiene a la semana: "))
if dia == 1:
print("el dia {} es el lunes".format(dia))
elif dia == 2:
print("el dia {} es el martes".format(dia))
elif dia == 3:
print("el dia {} es el miercoles".format(dia))
elif dia == 4:
... |
3688efb525b2f921c28cd1e83630a6aa6ddfda72 | hhonor5x/Pythonlearning | /Day1/Python-Tuples.py | 789 | 4.4375 | 4 | ##Python Tuples
##
##Tuple is an immutable list, i.e. a tuple cannot be changed once it has been created.
##
##Once a tuple is created we can't add or remove elements in the tuple
##
##benfits of tuples
##
##> Tuples are faster than lists.
##> If you know that some data doesn't have to be changed, we can use tuples ins... |
097bccc5a4d993487e0bc5265f18912037124839 | JaehoonKang/Computer_Science_110_Python | /FinalProject/Guess.py | 2,084 | 4.09375 | 4 | from tkinter import *
import random
class GuessingGame:
def __init__(self):
self.__window = Tk()
self.__answer = random.randint(1,99)
print(self.__answer)
def get_value():
number = self.__entry_guess.get()
if int(number) < self.__answer:
... |
140ecb535d52a8430dfd18709365d459de13c204 | srinidhi82/LPTHW | /fstrings.py | 467 | 3.53125 | 4 | #This is fstrings
my_name = 'zed'
my_height = 169 #cms
my_age = 38
my_weight = 75 #kiloa
my_hair_color = 'black'
total = my_age + my_height + my_weight
inch = 10
cms = inch * 2.54
pi = 8.7333
print(round(pi))
print(f"Lets talk about {my_name} now.")
print(f"I am now {my_weight} kgs")
print(f"I am {my_height} cms tall... |
7d29accdcfa843d225ef715d118b9c7f6c3add2c | jaden/2014-hour-of-code | /python/math_quiz.py | 243 | 3.828125 | 4 | from random import randint
x = randint(1, 12)
y = randint(1, 12)
answer = x / y
your_answer = int(raw_input("What is %d / %d? " % (x, y)))
if answer == your_answer:
print "Correct!"
else:
print "Whoops, the answer is: %d" % answer
|
bd5cdbb28cea3972dabd6f53e7889ff4dc0377a1 | AngeloBalistoy/Personal-Projects | /Python/CollatzConjecture/CollatzConjecture.py | 3,443 | 4.875 | 5 | # Collatz Conjecture: Start with a number n > 1. Find the number of steps it takes to reach one using the following
# process: If n is even, divide it by 2. If n is odd, multiply it by 3 and add 1.
opening_message = ("Hello! This script is related to all things Collatz Conjecture I am bothered to think about. Please"
... |
3bd2cd00af74191ad70c81f0a3d2f1bdb1bb7d80 | Paolo1984/test | /magic_number.py | 3,937 | 3.984375 | 4 | from random import *
import time
x = randint(1,20)
def intro():
print("Welcome to the slot machine!!")
print("Enter your name:")
a=str(input())
print("Hey " + a + " let me introduce you to this simple game..")
rules()
def rules():
... |
052f3c41b05fd43566229e3851a5b52870b8ed18 | 2324593236/MyPython | /Python基础/TCP/TCP服务器.py | 735 | 3.71875 | 4 | ###TCP
##创建TCP服务器
import socket#调用socket套接字模块
host = "127.0.0.1"#设置主机IP地址
port = 8080#设置端口号
tcp_server = socket.socket()#创建套接字
tcp_server.bind((host,port))#绑定IP地址和端口号,元组类型参数
tcp_server.listen(5)#监听,最大监听数量5
print("服务器等待连接")
while True:#死循环
conn,addr = tcp_server.accept()#等待接收,conn另一个socket对象,addr连接客户端的IP地址... |
96d4610f60522759087eb7a3ba64d30ea38b7744 | maxpt95/6.00.1xPython | /Unit 5/genPrimes.py | 454 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 19 21:35:04 2021
@author: maxpe
"""
def genPrimes():
prime = 2
i = 2
while True:
if prime % i == 0:
if i != prime:
i = 1
prime += 1
else:
yield prime
... |
e2d727393768d60622565fe1f732ecc1c9926ac9 | K-Wojciechowski/birthday-greetings | /tests/test_list_reader.py | 1,022 | 3.734375 | 4 | """Test the list reader."""
import datetime
import unittest
from birthday_greetings.reader.list_reader import ListReader
from tests import SAMPLE_FRIENDS
class TestListReader(unittest.TestCase):
"""Test the list reader."""
def test_basic_data(self):
"""Test reading basic data."""
reader = Li... |
72aad7f973c1c70479792799469323ae90ef6ba9 | A44em/Data-structures-algorithms | /binary_search_tree.py | 7,057 | 4.28125 | 4 |
class _node:
def __init__(self, data):
self.data = data
self.left_child = None
self.right_child = None
class binary_search_tree:
def __init__(self):
self.root = None
def insert(self, data):
"""
description:
This method inserts da... |
0624d32f9ce8c5e5e7ea0fafc4d558a829fb2406 | Ronaldsantillan/TRABAJO-DE-INVESTIGACI-N | /Ejercicio 1/menu.py | 3,692 | 4 | 4 | class Menu:
def __init__(self,titulo,opciones=[]):
self.titulo=titulo
self.opciones=opciones
def menu(self):
print(self.titulo)
for opcion in self.opciones:
print(opcion)
opc=input("Elija opcion[1...{}]: ". format(len(self.opciones)))
return o... |
deb97d67869bdc3a48f6026151e55b0ffde575b9 | charmipatel06/coffee-machine | /Topics/For loop/Vowel count/main.py | 200 | 3.9375 | 4 | string = "red yellow fox bite orange goose beeeeeeeeeeep"
vowels = 'aeiou'
total_vowels = 0
for i in vowels:
for j in string:
if i == j:
total_vowels += 1
print(total_vowels) |
ba73eb1757f91af25b53f844269cdd10984ef4e9 | xtinaushakova/redesigned-octo-chainsaw | /lab02/lab_02_01.py | 2,945 | 4.1875 | 4 | '''
Условия
'''
#if..else
num = int(input("How many times have you been to the Hermitage? "))
if num > 0:
print("Wonderful")
print("I hope you liked this museum!")
else:
print("You should definitely visit the Hermitage!")
#if..elif..else
course = int(input("What is your course number?"))
if course == 1:
print("Y... |
43250733a1fceec30014b2933c60577d0ed60927 | JennieOhyoung/interview_practice | /nuts(158)/nuts.py | 4,536 | 4.15625 | 4 | """
A pile of nuts is in an oasis, across a desert from a town. The pile
contains 'N' kg of nuts, and the town is 'D' kilometers away from the
pile.
The goal of this problem is to write a program that will compute 'X',
the maximum amount of nuts that can be transported to the town.
The nuts are transported by a hors... |
e571c791d4211cb9c4848c1e49df09d63122019c | PhotonicGluon/Advent-Of-Code-2020 | /Day 12: Rain Risk/day12-part1.py | 1,179 | 3.734375 | 4 | """
day12-part1.py
Created on 2020-12-12
Updated on 2020-12-12
Copyright © Ryan Kan
"""
# INPUT
with open("input.txt", "r") as f:
lines = [line.strip() for line in f.readlines()]
instructions = [(line[0], int(line[1:])) for line in lines]
f.close()
# COMPUTATION
# Execute instructions in order
movements... |
ebe535d8c1b4ed1098e4b9cb24f086e1b68c8ad3 | alter-mind/Edu_Gaddis_Python | /5ChapterExercises/KilometerConverter.py | 367 | 3.859375 | 4 | MILES = .6214
def convert():
return get_valid() * MILES
def get_valid():
kilometer = float(input('Введите расстояние в километрах: '))
while not(kilometer > 0):
kilometer = float(input('Введите корректное (положительное) значение в километрах: '))
return kilometer
|
f2ff585f7f18f570319e77f13fa1bcbf64575ed3 | yarivgdidi/num2string | /num2string.py | 2,406 | 4.03125 | 4 | dict = [
['אפס', 'אחת', 'שתיים', 'שלוש', 'ארבע', 'חמש', 'שש', 'שבע', 'שמונה', 'תשע'],
['עשרה', 'עשר', 'עשרים', 'שלושים','ארבעים', 'חמשים', 'שישים', 'שיבעים', 'שמונים', 'תשעים'],
['מאות', 'מאה', 'מאתיים' ],
['אלפים', 'אלף', 'אלפיים']
]
def oneDigit(digit):
return dict[0][digit]
def twoDigits(first,... |
4168e4a869088d9674627c0e75c168990f279eb5 | nicholask98/assignments-from-coder-pete | /4-2/4-2-1.py | 415 | 3.5625 | 4 | class Star:
def __init__(self):
print('A star is born!')
class Monster:
def __init__(self, name, health):
self.name = name
self.health = health
def main():
star_1 = Star()
star_2 = Star()
zombie = Monster(name='Zomboid', health=100)
spider = Monster(name='Spidoid', hea... |
1c0c9415e6dc9e98d78ad7d2893c610aa447ef0f | HanseamChung/practice | /부호판별기.py | 335 | 3.921875 | 4 | a=int(input('첫번째 숫자를 입력하시오'))
b=int(input('두번째 숫자를 입력하시오'))
if a ==0 or b ==0 :
print('0은 입력할 수 없습니다.')
else :
if (a>0 and b<0) or (a<0 and b>0) :
print(' 두 수의 곱은 음수입니다.')
else : print('두 수의 곱은 양수입니다.')
|
f0b7c146ceee50898fac3decc2760a09d48ac780 | sendador/Challenge | /Chapter 2/chapter_2.py | 4,541 | 3.734375 | 4 | import sqlite3
import argparse
from datetime import date
class Task:
def __init__(self, name, deadline, description):
self.name = name
self.deadline = deadline
self.description = description
conn = sqlite3.connect('task.db')
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS tasks... |
7362324162423492fccd7a1d3542799b9e9ff916 | jarvis2411/guvi | /hands-on/python/22.01.2020/contact manager.py | 142 | 3.828125 | 4 | a = {'Praghadesh':'9943086688','Nishanth':'7084619021'}
b = input("Enter the name to display the phone number:")
if b in a:
print(a[b])
|
f5dc95da595c0b9e268f1eecdbba9a23e056cea2 | zzy1120716/my-nine-chapter | /ch02/0458-last-position-of-target.py | 1,017 | 4 | 4 | """
458. 目标最后位置
给一个升序数组,找到target最后一次出现的位置,
如果没出现过返回-1
样例
给出 [1, 2, 2, 4, 5, 5].
target = 2, 返回 2.
target = 5, 返回 5.
target = 6, 返回 -1.
"""
class Solution:
"""
@param nums: An integer array sorted in ascending order
@param target: An integer
@return: An integer
"""
def lastPosition(self, nums... |
43278760edbab2a5a2782f58a66940fd625744d9 | jvalentee/lightningRoutingStudy | /simulation/shortestpathrouting.py | 1,313 | 3.671875 | 4 | import networkx as nx
class ShortestPathRouting:
def __init__(self, G):
self.G = G
return
# Simulate the payment and change the channel states accordingly. If the path is not valid return -2. If the payment
# was successful then return 0
def simulatePayment(self, source, destination... |
ccba14f9cb4347d78c4d14b4e7f4e0071de4135a | mpzaborski/trj | /server/monoclient.py | 2,861 | 3.9375 | 4 | # This file contains the information for creating a socket for EACH
# of the clients, it also contains the CLient class itself that is managed from the
# server file (see server.py)
class Command:
"""
Stores information about the every single command of the client.
"""
def __init__(self, command, resu... |
6b02da824ee9c4ec888e69ebdfea4cb0da44617e | ogabriel/python_CS | /exercises_p1/ex_6.py | 137 | 4.125 | 4 | num = int(input('Digite um numero: '))
for n in range(0, 11):
result = num * n
print("{0} X {1} = {2}".format(n, num, result))
|
e049c23c6021e470304c133836a5500b5a27b749 | Termich/All | /Ch1/Lesson_4(Input in Phyton 1).py | 968 | 4.1875 | 4 | #Создайте функцию, принимающую на вход имя, возраст и город проживания человека.
# Функция должна возвращать строку вида «Василий, 21 год(а),проживает в городе Москва»
def life(name,year,city):
information =(f'Вас зовут {name}, вам {year} год(а), вы проживаете в городе {city}') #Создаем функцию, где отмечаем арг... |
612afefda79b57ee8a78d9f01a3353449b7591df | pmalav/Unscramble-Computer-Science-Problems | /Task3.py | 2,842 | 4.15625 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 3:
(080) is the area code for fix... |
ad832f3faeb40373c438f2609f7cf0681e7fed78 | RoussillonB/INF-101-2020 | /TD2/ex_12_avec_fonctions.py | 2,196 | 4.03125 | 4 | def question_1():
# First question of the quzz
rep = input('a < b < c ?')
# Translates user answer into boolean
bool_rep = rep == 'V'
true_answer = a < b < c
# The user is correct if and only if their answer is the same as the true answer
return true_answer == bool_rep
def question_2():
... |
97069183e0ef4693225cc0233e3a97ebd9533b25 | gergely-k5a/building-ai | /3. Machine learning/3. Working with text/18. tf-idf.py | 1,989 | 3.703125 | 4 | import numpy as np
import math
# Term Frequency Inverse Document Frequency
text = '''Humpty Dumpty sat on a wall
Humpty Dumpty had a great fall
all the king's horses and all the king's men
couldn't put Humpty together again'''
# distance function
def getDist(a, b):
sum = 0
for ai, bi in zip(a, b):
su... |
0d33deb3911ed7efe3e87c151ad071d8dceef3be | novayo/LeetCode | /Tutorials/example_tuple.py | 260 | 3.78125 | 4 | a = (10,20)
# Can not Change length
# a.append(1) # crash here
# Change value
# a[0] = 10 # TypeError: 'int' object does not support item assignment
print(a) # # (10,20)
# Cannot be hash
hash_table = {}
hash_table[a] = 99
print(hash_table) # {(10, 20): 99} |
46764da1c2a919b7a39b78ec6674aa2da41d058f | brianfl/Euler | /26.py | 923 | 3.875 | 4 | def is_prime(current_primes, potential):
counter = 0
for i in current_primes:
if potential % i == 0:
counter += 1
if counter == 0:
return True
else:
return False
prime_list = [2]
for i in range(3, 1001):
if is_prime(prime_list, i):
prime_list.append(i)
... |
a61789c6b7971ddb9646e7061df92d7e3447232a | sebastianagomez/Programming-Building-Blocks | /Week 10/teamActivity_10.py | 1,146 | 3.96875 | 4 | nameBanks = []
bankBalances = []
bankItem = ""
balanceItem = ""
print("\nEnter the names and balances of bank accounts (type: quit when done)\n")
while bankItem != "quit":
bankItem = input("What is the name of this account? ")
if bankItem != "quit":
balanceItem = float(input("What is the bal... |
e50bdbb27ed6cb65eeaaf4752b349aac3839be41 | coding-hamster/Udacity-Programming-Foundations-with-Python | /turtle_scripts.py | 549 | 3.546875 | 4 | import turtle
window = turtle.Screen()
window.bgcolor('red')
def draw_square():
brad = turtle.Turtle()
for i in range(1, 5):
brad.forward(100)
brad.right(90)
draw_square()
def draw_circle():
window = turtle.Screen()
angie = turtle.Turtle()
angie.shape('arrow')
... |
fe89f81d491b27e3d297d1d3d220b17376f28df1 | BrunoCodeman/desafioluizalabs | /search.py | 798 | 3.578125 | 4 | import glob
import sys
from pathlib import Path
def search_content(content):
"""
Returns a list with all the .txt files inside the data directory that have the given string
"""
files_to_search = glob.glob("data/*.txt")
readfile = lambda fp: Path(fp).read_text()
check = lambda file: con... |
668bd5f6991fdf9f4a39a1a5981feab5dc03b197 | andrewkucharavy/luigi-course-materials | /tasks/yellow_taxi/sqlite_query.py | 546 | 3.84375 | 4 | """
скрипт делает запрос в sqlite.db и получает день в котором было больше всего чаевых
"""
import sqlite3
if __name__ == '__main__':
conn = sqlite3.connect('sqlite.db')
cur = conn.cursor()
for row in cur.execute(
"""
select pickup_date,
tip_amount,
total_amou... |
54ff924382dff4d20ddc8d5c9e593ce36441ff11 | pritam13/Python_code | /jsonTry.py | 354 | 3.625 | 4 | import json
#converting text to dictionary
a='{"Name":"Pritam","Age":30,"Address":"Jaugram"}'
b=json.loads(a)
print(b["Name"])
print(b["Age"])
#converting all datatypes to json
c= {
"name":"Pritam",
"Age":30,
"Employes":True,
"Hobby":("Movies","Sports"),
"pets":None,
"Cars":[{"Model":"BMW","mpg":27.... |
8cd11de1d8804f3a65a3a0b08e608e3389949a5c | RishitAghera/internship | /pythonTest/torrentbill.py | 3,597 | 3.96875 | 4 | def rgp(unit):
phase=int(input("Enter Phase: 1 for single and 3 for three phase:"))
while phase not in (1,3):
phase=int(input("Please enter correct phase '1' or '3'."))
amt=0.00
if 0<=unit and unit<=50:
amt+=unit*320
elif 51<=unit and unit<=200:
amt+=16000
amt+=... |
ebbd5b1882815215928fa47b5e64a8f1021aa510 | KrishnadevAD/Python | /u2.py | 76 | 3.6875 | 4 | stringVar="33.66"
number=5
number3=float(stringVar)*number
print(number3) |
18435bf3af045b4c417b29c98f548a1f74483f2b | dayepesb/OnlineJudges | /src/ProblemsIn_Python/Metodos/Teller1/Punto3.py | 263 | 3.59375 | 4 | '''
Created on 14 ago. 2017
@author: david
'''
def numerosTriangulares(n):
i = 1
for i in range(n):
print (i * (i + 1)) / 2
pass
if __name__ == '__main__':
print 'Ingrese el numero n'
n = input()
numerosTriangulares(n)
pass
|
941f9000d8597f614d32a9818bea955bf7fd5deb | Ag-Y2/dv_pythonApp | /_class.py | 1,099 | 3.6875 | 4 | # -*- coding: utf-8 -*-
class Cup:
def __init__(self, t):
self.count = t
def getcount(self):
return self.count
def setcount(self, n):
self.count = n
mall_nameList = []
mall_qtyList = []
class Mall:
def __init__(self):
self.mallname = "mallName"
self.mallcount =... |
1ba72074a17b704e7cf91738edee40148c75302c | TrisAXJ/py-study | /demo1/demo4.py | 1,802 | 3.65625 | 4 | # -*- codeing = utf-8 -*-
# @Author:TRISA QQ:1628791325 trisanima.cn
# @Time : 1/11/2021 10:24 PM
# @File : demo4.py
# @Software: PyCharm
'''
for i in range (5):
print(i)
'''
'''
for i in range(0, 10, 2):
print(i) # 输出为 0 2 4 6 8 ;步进完判断 <10
'''
'''
for i in range(-10, -100, -20):
print(i)
'''
'''
n... |
4cdd134fdad9d9a57fb80559e9ca83baa70e3281 | rockcoolsaint/bootcamp | /problem4.py | 805 | 3.859375 | 4 | def fibonacci(num):
fib_list = [0,1]
while len(fib_list) < num:
x = fib_list[len(fib_list)-1]
y = fib_list[len(fib_list)-2]
fib_list.append(x + y)
return fib_list
def fibo_sum(num, radix=None):
fib_list = [0,1]
while len(fib_list) <= num:
x = fib_list[len(fib_list)-1]
y = ... |
b4411cd464c76de078be98fd657da2a9610f9b01 | rafaelperazzo/programacao-web | /moodledata/vpl_data/465/usersdata/299/112303/submittedfiles/Av2_Parte4.py | 813 | 3.984375 | 4 | # -*- coding: utf-8 -*-
n=int(input('Determine a dimensão da matriz quadrada A: '))
A=[]
for i in range(n):
linha=[]
for j in range(n):
linha.append(int(input('Digite o elemento %d x %d da matriz A: '%(i,j))))
A.append(linha)
c=int(input('Digite a quantidade de cidades do intinerário: '))
while c<2:... |
095e6e09e9d75b4f808b87b353770bb53d4fc1f7 | Kattyabo/BootCamp_Python_Modulo2 | /M2_S2_ind/pregunta_M2_t2.py | 250 | 3.859375 | 4 | #1. Investigue sobre la función input() en Python y cómo se utiliza.
'''La función input() permite a los usuarios introducir datos de distintos tipos
desde la entrada estándar (normalmente se corresponde con la entrada de un teclado).
''' |
e12382bdf9529122de0137a65b74c383150a164b | aflah02/BeginnerPythonProjects | /RockPaperScissorsGame.py | 1,784 | 3.734375 | 4 | import random
ls = ['Rock', 'Paper', 'Scissors']
while True:
k = int(input("How Many Times do You Want to Play?"))
player_score = 0
comp_score = 0
for i in range(k):
comp_choice = random.choice(ls)
print(comp_choice)
player_choice = input("Choose one of Rock, Paper or Scissors")
... |
57b3f847aa1d8a5f1c47e1136acfef1e6e77698c | ZhongruiNing/ProjectEuler | /Code of ProjectEuler/problem27.py | 1,084 | 3.828125 | 4 | from math import sqrt
def isprime(num):
# flag=1,素数,flag=0,合数
flag = 1
if num == 2:
return flag
for i in range(2, int(sqrt(num)) + 1, 1):
if num % i == 0:
flag = 0
return flag
return flag
result = 0
result_a = 0
result_b = 0
for a in rang... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.