blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
16fc19a79917a581f4ef3571485471a159f1d3e4 | TudroVilin/PYTHON | /numeromayor.py | 300 | 3.828125 | 4 | print("Introduzca el primer número:")
n1=int(input())
print("Introduzca el segundo valor:")
n2=int(input())
if(n1>n2):
print(str(n1)+" es mayor que "+str(n2))
elif(n1==n2):
print(str(n1)+" y "+str(n2)+" son iguales")
else:
print(str(n2)+" es mayor que "+str(n1))
print("Fin de programa") |
b307cae1c33261177b08212dd16864603cf0122a | Matt711/anime_reference | /anime_reference/anime_objects/utils.py | 2,284 | 3.53125 | 4 | from re import search, findall
from bs4 import BeautifulSoup
from typing import List
def clean_str_list(list_str: List[str], search_str: str = '"(.*)"') -> List[str]:
"""
Description: "Cleans" a list of strings using regex based on
on a search string.
Parameters:
-----------
list_... |
c996ec67271d7686e47eabff7dc9633b261596ff | ushadevipatturaj/HyperSkillPythonCodesScenarios | /venv/Data/Coffee_Machine.py | 749 | 4.3125 | 4 | # Write your code here
print("Write how many ml of water the coffee machine has:")
water = int(input())
print("Write how many ml of milk the coffee machine has:")
milk = int(input())
print("Write how many grams of coffee beans the coffee machine has:")
coffee = int(input())
print("Write how many cups of coffee you will... |
576f2d139cab34f1d5c01f3e8921d2f43d66d26b | ak795/acm | /spoj/SCAVHUNT/1.py | 382 | 3.59375 | 4 | for i in range(int(input())):
print('Scenario #{0}:'.format(i + 1))
nonroot = set()
d = {}
for j in range(int(input()) - 1):
s = input().split()
d[s[0]] = s[1]
nonroot.add(s[1])
for root in d:
if root not in nonroot:
break;
while root in d:
p... |
4fedfa4819f2529b8b84a92a8e20cc1d1b9a1b73 | michalkalinowski-/StdProblems | /optimal_decision.py | 5,453 | 4.125 | 4 | # F O X E S A N D H E N S
# Example of defining an optimal strategy when playing a game based on a random event
# -----------------------------------------------------------------------------------
# This code is derived from one of the homeworks I completed for Peter Norvig's
# *Design of Computer Programs* class ... |
0016e4334d67696ac139e3cdb1e4226b33a3c178 | Shimpa11/PythonTutorial | /session44.py | 3,114 | 4.4375 | 4 | """
Unsupervised Learning
We have data but no labels !!
Classification will be numerically done by the model and we later name those classes
Output is not known for observations in the dataset
k-means clustering
k here denotes number of classes we expect from model after classification
-----... |
16f0c1c00d457e412636c393f9e050d8929f9c7a | gusatb/split-py | /game.py | 19,603 | 4 | 4 | """Game logic for Split.
Rules:
Game starts with a square of neutral colored lines.
(Pie rule for first move?)
Players take turns drawing line segments of their color with each endpoint touching preexisting lines and not crossing any lines.
Endpoints of lines cannot be placed on intersections.
If b... |
736cec9862a48f3789776e9a631ed5ce9ad11050 | Thearakim/int_to_bin | /int_to_bin.py | 606 | 4.4375 | 4 | def int_to_binary(a, b): #function take two paramaters
sum = a + b #sum two number take from print
temBi = "" #declare string "" for adding the code below
while sum != 0: #using loop to make sure a and b is greater than 0 because equal 0 error
temBi = str(sum % 2) + temBi #first it calcula... |
44ea22d11697fe7b59f85775d99a8c7fb519812e | lschock/python | /collection_challenges.py | 1,137 | 4.15625 | 4 | # Challenge Task 1 of 2
# Create a function named square. It should define a single parameter named number.
# In the body of the function return the square of the value passed in.
# (A square is the value multiplied by itself. eg: The square of 5 is 25. 25 = 5 x 5)
def square(number):
value = number * number
r... |
e3e69d274c08baaaf05e776a451af261374eedb9 | warleyken42/estrutura-de-dados | /lista_03/exercicio08.py | 804 | 3.671875 | 4 | class Macaco:
def __init__(self, nome):
self.nome = nome
self.bucho = []
def comer(self, objeto):
self.bucho.append(objeto)
def verBucho(self):
print("Coisas no Bucho: ")
for i in self.bucho:
print(i)
print("...")
def digerir(self):
... |
767c0ccdded4a985ae8679c00ef5b4159ea9b41d | mehmetatesgit/pythonkurs | /class.py | 1,065 | 4.3125 | 4 | '''
#class
class Person:
# class attributes
address = 'no information'
#constructor (yapıcı metod)
def __init__(self, name, year):
#object attribute
self.name = name
self.year = year
# methods
def intro (self):
print('Hello There I am '+ self.n... |
e1b23f89ca96196315eb7e92762a3982a69b38b5 | generocha/ITC110 | /week7/weekly_wage.py | 1,267 | 4.21875 | 4 | '''
Peer Assignment 6
Calculate weekly wage with functions
1. Get hours worked
2. Get hourly wage
3. Calculate regular pay
4. Calculate overtime pay
5. Calculate weekly pay
6. Print result
Gene Rocha
11/5/2019
'''
REGHOURS = 40
# get the hours worked
def getHours():
hours = int(input("Enter the hours worked for the... |
13cbbf688ca760d5b6f98c3970ac5f7ee8843789 | wangyendt/LeetCode | /Contests/201-300/week 297/2303. Calculate Amount Paid in Taxes/Calculate Amount Paid in Taxes.py | 752 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 _*-
"""
@author: wangye(Wayne)
@license: Apache Licence
@file: Calculate Amount Paid in Taxes.py
@time: 2022/06/12
@contact: wang121ye@hotmail.com
@site:
@software: PyCharm
# code is far away from bugs.
"""
from typing import *
class Solution:
def calculateTax(s... |
fe58fa2e31a454fd8f152a703ee71e38276e3121 | kpberry/minimum-vertex-cover-algorithms | /hill_climbing.py | 6,532 | 3.8125 | 4 | # File containing our implementation of a variation on randomized hill climbing.
# Uses two neighbor functions: get_close_neighbor, which tries to remove a
# random vertex from a VC if doing so will keep the VC a solution, and
# get_neighbors, which removes 0 to 3 random vertices from a graph if it is a
# solution or a... |
6e0893aba1a4d8ff9341538a505f8ef2d47c16bd | vijay0423/project1 | /python program implemented by using comments to easily understand.py | 1,991 | 4.28125 | 4 | x=100#Global Variables
y=200
class X:#Super class(X)
"""sample class to test basic concepts of python programs"""#Documentational string it is a optional statement
a=300#Static Variables
b=400
def __init__(self):#Constructor To initialize the nonstatic variables
pri... |
511a742b7f27dc0379d65090f25ec91375f0b2d9 | VisionAILab/Training | /Anudit Bhatt/Python_OOPs/Ex4.py | 745 | 3.953125 | 4 | class Computer:
def __init__(self):
self.name = "Anudit"
self.age = 21
def update(self):
self.age = 26
def compare(self,other):#compare(who is calling, whom is calling)
if self.age == other.age:
return True
else:
retur... |
b70dcfe75ba4585c3a840afa58d5992377acf27e | walstra/phd_nikhef | /slides/bubblesort_dbg.py | 407 | 4.0625 | 4 | import random
def display_list(l):
for value in l:
print("**" * value)
input("")
def bubblesort(l):
for left in range(len(l)-1,0,-1):
for i in range(left):
if l[i] < l[i+1]:
l[i], l[i+1] = l[i+1], l[i]
display_list(l)
return l
l = [random.randrange(1,... |
93f056e361928986f3c011df6f2c2873ba8a3402 | LucasLeone/tp2-algoritmos | /ciclo_while/cw1.py | 155 | 3.609375 | 4 | '''
Leer una serie de cincuenta números enteros.
'''
import random
i = 0
while i < 50:
i = i + 1
num = random.randint(0, 100)
print(num) |
e4a5f9a05ddf95e329abb9d80dea1b3b83e2a782 | henmanzur/Python | /Exercises/Exercise3_Strings_and_ConsoleOutput.py | 2,031 | 3.859375 | 4 | ############
# # מחרוזת
############
'''
מחרוזות(STRINGS) הן משתנה המתאר רצף של תווים
(אותיות, מספרים וערכים שונים של ביטויים כמו רווח,סימן קריאה וכו')
ההכרזה על משתנה מסוג מחרוזת נעשית באמצעות מרכאות או גרשיים
hen = 'hen manzur'
hen2 = "hen manzur"
'''
#hen3 = '''
# hen manzur
# '''
#hen4= """
# hen manzur
# """
'''
... |
bbefa9841031f810cb756d5f76c0396ca0141ce0 | saequus/learn-python-favorites | /Tasks/GetDigitPart.py | 1,499 | 3.921875 | 4 | # Return part with digit(s) if the string starts with one.
def get_digit_part(string) -> int:
""" Returns part with digit(s) if the string starts with one.
:param string:
:return int:
"""
negative = False
punctuation_set = {
'~', ':', "'", '+', '[', '\\', '@', '^', '{', '%', '(', '-', ... |
284b69789595832fd82ab28133a6855848df00ca | ashiqks/Data-Structures-Algorithms | /Linked_Lists/Singly_Linked_List.py | 15,301 | 4.03125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[235]:
# Class to create a node for singly-linked list
class Node:
def __init__(self, data):
# Variable to hold the data point
self.data = data
# Reference for the next node
self.next = None
# In[252]:
class SinglyLink... |
f8063f6f47184d1d0a4039524861605ad8dd6c11 | alv2017/Python---YahooFinanceDataLoader | /YahooFinanceDataLoader/utils/set_time_point.py | 562 | 3.90625 | 4 | import datetime
def set_time_point(dt):
"""
The function takes date as an input and returs
a timestamp in seconds
Input: date, format "yyyy-mm-dd"
Return: date timestamp in seconds since 1970-01-01
"""
year, month, day = dt.split("-")
# input date is valid
tr... |
fcbf1da11a4716ef13b1cc556e508d55b7b11797 | MercybirungiS/PYTHON-CLASSES | /PyQuiz/python_test.py | 1,619 | 3.796875 | 4 | # Number 1
from typing import AsyncGenerator
x = [100,110,120,130,140,150]
y=[]
a=1
for a in x:
a=a*5
y.append(a)
print (y)
# number 2
def divisible_by_three (n):
x=range(n)
for i in x:
if i %3==0:
print(i)
divisible_by_three(15)
# number 3
def flatten():
x = ... |
f9bac027b8ada7e760d6d4edf2bc7f480ea4726b | arogers1/VBPR | /utils.py | 628 | 3.796875 | 4 | def bsearch(a, x, reverse_sorted=False):
left, right = 0, len(a) - 1
while left <= right:
mid = left + (right - left) // 2
if a[mid] == x:
return mid
if reverse_sorted:
if a[mid] >= x:
# go right
left = mid + 1
else:
right = mid - 1
else:
if a[mid] >= x:
# go left
right = mid -... |
8035a412e96e819592f572bf50cd019bfe6e4195 | alirezataleshi/project | /bmi standard.py | 689 | 4.0625 | 4 | unit= input("aya metric estefade mikonid?:")
if unit=="y":
weight = float(input("weight in metric?:"))
height= float(input("height in metric?:"))
bmi = weight / (height * height)
print(bmi)
if bmi > 30: print("obesity")
if bmi < 18.5: print("underweight")
if 18.5 < bmi < 25: print("normal... |
e75559fa1d15a4e8093d16b417bbfb6ef701cc5d | mekcherie/CS1.1OOP | /instructor.py | 1,402 | 3.640625 | 4 | from School import School
from manager import Manager
from students import Students
class Instructor(School):
def __init__(self, name, year, address, id, title, class_names, salary=3000):
super().__init__(name, year, address, id)
self._title = title # protected bc we only want it to be accessed fr... |
13f7693d11c6a081ce4124c253f74f3caf788637 | Leo7890/Tarea-04 | /Áreas de rectángulos.py | 2,122 | 3.921875 | 4 | #encode: UTF-8
#Autor: Leonardo Castillejos Vite
#Descripción: programa que lee los lados de 2 rectángulos y entrega el perimetro y el área.
import turtle
def main():
largo1 = int(input("Teclea el largo del rectángulo 1: "))
ancho1 = int(input("Teclea el ancho del rectángulo 1: "))
perimetro1 =... |
48253bc7e52d88290f101573c26132a59ae6e5ec | changrif/CIS4930_PPA1 | /console/console.py | 2,893 | 4.09375 | 4 | from main import bmi, shortestDistance, email, tab, db
def run():
choice = -1
while(choice != "5"):
choice = raw_input(
"**********************"
"\nFunction Menu: "
"\n (1) Body Mass Index"
"\n (2) Shortest Distance"
"\n (3) Ema... |
4232c9a680a5c0afd57c73207354b33a62bf4c67 | Chaguin/PruebasPython | /PRUEBAS2/PRUEBAS PYTHON 2/str_punto.py | 247 | 3.609375 | 4 | # -*- coding: utf-8 -*-
class punto:
def __init__(self, x,y):
self.x=x
self.y=y
def __str__(self):
return "("+str(self.x)+", "+str(self.y)+")"
punto1=punto(10, 3)
punto2=punto(3, 4)
print (punto1)
print (punto2)
|
84a0f57e19b16703a89249f20f15ecae04865fc3 | AntoniyaV/SoftUni-Exercises | /Fundamentals/04-Functions/03-character-in-range.py | 261 | 3.859375 | 4 | def characters_in_range(char1, char2):
chars_str = ''
for i in range(ord(char1) + 1, ord(char2)):
chars_str += chr(i) + " "
return chars_str
character_1 = input()
character_2 = input()
print(characters_in_range(character_1, character_2)) |
fc85059fa8de5888bfe5ccac1950cf157a3e0693 | rakshit6432/HackerRank-Solutions | /30 Days of Code/Python/27 - Day 26 - Nested Logic.py | 668 | 3.609375 | 4 | # ========================
# Information
# ========================
# Direct Link: https://www.hackerrank.com/challenges/30-nested-logic/problem
# Difficulty: Easy
# Max Score: 30
# Language: Python
# ========================
# Solution
# ========================
DAY_1, MONTH_1, YEAR_1 = map(int, input... |
7d30a9d566872924a17b4c61c4e7b0ec29f4c7ec | GSimas/PyThings | /Coursera/Python for Everybody/2-Data Structures/assignment7_2.py | 470 | 4.125 | 4 | ## Python for Everybody Coursera
## Assignment 6_5
## Gustavo Simas da Silva - 2017
## Python Data Structures, String Manipulation, File handling
# Use mbox-short.txt as the file name
fname = input("Enter file name: ")
fh = open(fname)
result = 0
n = 0
for line in fh:
line = line.rstrip()
if 'X-DSPAM-Confidenc... |
f75edc2a86e9a9456ea654f80de3ab3da6e1fb44 | Erickmarquez7/python | /funciones/adivina.py | 915 | 4.1875 | 4 | import random
"""
El usuario adivina el numero al azar producido por la computadora
La computadora genera un numero al azar en un rango determinado por el usuario,
el objetivo es adivinar dicho numero
Para ejecutarlo solo es necesario utilizar el interpretador de python
python3 adivina.py
"""
def adivina(x):
"... |
2337b326b1cb213ea75b1ef833441540bafa1b41 | Rahul0506/Python | /Worksheet1/18.py | 955 | 3.921875 | 4 | cent10In = int(input("Enter number of 10-cent coins inserted: "))
cent20In = int(input("Enter number of 20-cent coins inserted: "))
cent50In = int(input("Enter number of 50-cent coins inserted: "))
cent100In = int(input("Enter number of 1-dollar coins inserted: "))
drinkPrice = float(input("Enter price of drink (0.... |
641b862473d72835d6b905234969e7a3d35872e0 | MrHamdulay/csc3-capstone | /examples/data/Assignment_4/lkxant002/boxes.py | 807 | 3.953125 | 4 | def print_square():
print(5*"*",sep="")
print("*"," ","*")
print("*"," ","*")
print("*"," ","*")
print(5*"*",sep="")
def print_rectangle(w,h):
print(w*"*",sep="")
for i in range(1,h-1):
print("*",(w-2)*" ","*",sep="")
print(w*"*",sep="")
def get_rec... |
a84a4e53eb14695644d1f97e10771d8086833da6 | saifsafsf/Semester-1-Assignments | /Lab 05/task 5.py | 632 | 3.84375 | 4 | num = int(input('Enter number of rows: ')) # Taking Input
if num > 0:
for i in range(1, num+1):
for j in range(num-i): # Displaying Spaces
print(end=' ')
for k in range(i): # Displaying Asterisks
print('*', end=' ')
print()
# ESEs Prep.
for... |
a1385ce75f4fd37a083e44cd9ac0b620f6ffbd18 | pathankhansalman/LeetCode | /simplify-path.py | 1,137 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 10 23:20:14 2022
@author: patha
"""
class Solution(object):
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
if len(path) == 1:
return path
mystr = path
prev_len = len(mystr)
... |
2b62c3766c2235eea7d1cc72dbbc535fd04ac0e3 | bdnguye2/Python_scripts | /frags_cnt.py | 865 | 3.9375 | 4 | #!/usr/bin/python3
#
# This script reads in csv file (user input) and
# computes the total charge of fragments from
# Mulliken population analysis of the supermolecules.
# The csv file must be formatted with the following
# columns: Supermolecule, and Monomer A.
# In addition, the supermolecule coordinates must
# ha... |
d62ec7de1990969711771bcdbb9e01b8cad67ed4 | peinbill/leetcode_learning_card | /array/SolutionOffer29.py | 1,331 | 3.609375 | 4 | from typing import List
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if matrix==None or len(matrix)==0:
return []
if len(matrix)==1:
return matrix[0]
row_num = len(matrix)
col_num = len(matrix[0])
num_count = row_num*co... |
459c4290559f1146196be19590e2b86e93a79ede | semensorokin/educational-nlp-projects | /ClientServerArchitecture/Day2_part_1_solutions/unit_test_examples.py | 232 | 3.734375 | 4 |
# return multiplication of two digits
def multiply(a, b):
return a*b
# return true if a point is in circle
# with radius 1 and center in (0, 0)
# including borders
def is_in_circle(x, y):
return x**2 + y**2 <= 1.0
|
24bb27e2f7279ab0648d61ec17d1bc7185d578d4 | riturajkush/Geeks-for-geeks-DSA-in-python | /Tree/Check if subtree.py | 4,120 | 4.09375 | 4 | #User function Template for python3
'''
class Node:
def _init_(self, val):
self.right = None
self.data = val
self.left = None
'''
# your task is to complete this function
# function should print the left view of the binary tree
# Note: You aren't required to print a new lin... |
3442e72a8d7131d66a85d35254978f64204b389b | Magssch/TDT4113-computer-science-programming-project | /project 2/ManyGames.py | 2,358 | 3.625 | 4 | from matplotlib import pyplot as plot
from Game import *
from Random import *
from Sequential import *
from MostFrequent import *
from Historian import *
class ManyGames:
# Setup game
def __init__(self):
self.p1 = self.setupPlayer(True)
self.p2 = self.setupPlayer(False)
self.num_games... |
1fe034fc8c1f9dced00f457ca3565a12163aadba | WuTang94/Cryptography-programs | /HW 7 Miller Rabin.py | 3,134 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Nov 18 09:36:05 2017
@author: Justin Tang unless otherwise stated;
methods that I borrowed online and modified are denoted
"""
import random
#import math
"""
I borrowed this method of Miller Rabin from a website, but I replaced the pow()
function with the Square and Multiply... |
189b5c54f70c5c7b774ac099e85421e7520c1424 | deepakkt/codility-training-python | /007-stacks-and-queues/codility-stacks-and-queues-4-manhattan.py | 1,220 | 3.875 | 4 | # you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(H):
# write your code in Python 3.6
# start with the first height
cuboid_stack = [H[0]]
blocks = 1
cuboid_sum = H[0]
# scroll through the 2nd onwards
for (idx, n) in enumerate(H[1:]):
... |
6140f5159480d8ad6e5522e851b27ad2fb473175 | pareshsalunke/sortingcodes | /insertion_sort.py | 356 | 4.1875 | 4 | def insertion_sort(list):
for index in range(1,len(list)):
value = list[index]
i = index-1
while(i>=0):
if (value < list[i]):
list[i+1]=list[i]
list[i] = value
i = i - 1
print list
def main():
list = [8,4,3,6,1,2]
insertion_sort(list)
if ... |
bbb64d37fa95e3c918c51558af3422f1fb6d77d1 | mrigankasaikia91119993/String-Functions | /find_string_elements.py | 527 | 4.28125 | 4 | ###The function find_alphanum(a, b) find if a given string's elements occured in n another string, takes two arguments , a is the string where elements are to be find and b is the string who's elements are to be find. This function is not case sensitive.###
def find_alphanum(A, B):
A.upper()
B.upper()
c = False
f... |
2bdae8cf4c3a6891c6f675ec5254fa5f75b5d845 | SUKESH127/bitsherpa | /[3] CodingBat Easy Exercises /solutions/string1 - alternate.py | 662 | 3.75 | 4 | def hello_name(name):
return 'Hello ' + name + '!'
def make_abba(a, b):
return a + b + b + a
def make_tags(tag, word):
return '<' + tag + '>' + word + '</' + tag + '>'
def make_out_word(out, word):
mid = int(len(out) / 2)
# note that the 0 is optional
# So this would also work:
# return out[:mid] + wor... |
d47de4eaaa9169ef7c6dd6e4ffd5e9121456e258 | AnjiSingh738/Task-1 | /TASK 1.py | 2,168 | 3.875 | 4 | #!/usr/bin/env python
# coding: utf-8
#
# # GRIP: The Sparks Foundation
# # Data Science and Business Analytics Intern
# # Author: Anjali Singh
# # Task 1: Prediction Using Supervised ML
# In this task we have to predict the percentage score of a student based on the number of hours studied. The task has twovaria... |
74e324b9e75effb439daf996e64c99372f4016d0 | mvargasmoran/interview-stuff | /python/friendlyElapsedExecutionTime.py | 1,977 | 3.53125 | 4 | # Requested by project waste not inc.
#
# Problem 1 (Python)
#
# Provide some Python code that can be used to measure how long a function takes to run in a friendly
# format. The amount of time can range from less than a second to several hours and should be easy
# for a human to read (for example “00:00:00:00012” is n... |
aa4e7199245b6784f40cfd7d22344f3640afba37 | Soumya1910/Competetive_Programs | /waveArray.py | 924 | 4.03125 | 4 | """
Problem Statement :
Given an array of integers, sort the array into a wave like array and return it,
In other words, arrange the elements into a sequence such that a1 >= a2 <= a3 >= a4 <= a5.....
"""
class Solution:
# @param A : list of integers
# @return a list of integers
def swap(se... |
a85d14f8eef7b8564179616cdf221da2368a6eb8 | savannahjune/wbpractice | /trees/binarysearchtree.py | 2,690 | 4.125 | 4 | class Node(object):
def __init__(self, value):
self.left = None
self.right = None
self.value = value
class BinarySearchTree(object):
def __init__(self):
self.root = None
def append_node(self, value):
new_node = Node(value)
if not self.root:
# if there's no root (e.g. th... |
4bfcf6cdacddbe31557305496ef4dde765617527 | AtharvaJoshi21/PythonPOC | /Lecture 22/Lecture22HWAssignment1.py | 641 | 3.515625 | 4 | # WAP to accept a command to be executed as a cmd line arg. Execute the command provided and print output of the same.
import optparse
import subprocess
def ExecCmd(inputCommand):
execCmdOutput = subprocess.check_output(inputCommand, shell = True)
return execCmdOutput
def main():
parser = optparse.OptionP... |
70498113dff682b485e812bb5b509ce9e3411100 | benjaminner/python-scripts | /bentrainsim.py | 888 | 3.875 | 4 | import time
cc = 0
dc = 0
now = time.time()
trntme = now + 30
stations = {'srrvyce':1,'tuomo':2,'leeo':3,'polutica':4,'orvochino':5,'loino':6,'ilumitcio':7}
po = raw_input("look at your current station. what is it's name? ")
if po in stations :
cc = stations[po]
else :
print("sorry, that is not a station")
... |
94c5bbbddff6732954fb54cb31ff13876926f78d | LZZimmerman/GamesProgramming | /Class 7/classwork1.py | 759 | 3.5 | 4 | import pygame
from pygame.locals import *
#initialisation, on all pygames
pygame.init()
pygame.display.set_caption("My first PyGame program")
screen = pygame.display.set_mode((640,480))
xpos = 100
ypos = 200
clock = pygame.time.Clock()
while 1:
pressed_key = pygame.key.get_pressed()
screen.fill((255,69,0))
... |
6c4ba1ede4d61ab2e47a9b7eb11f48867eb5c5e2 | dim272/coursera_python | /solution2.py | 455 | 3.8125 | 4 | import sys
value = int(sys.argv[1])
initial_value = value
result = []
while value > 0:
number_of_spaces = value - 1
number_of_octohorpe = initial_value - number_of_spaces
while number_of_spaces > 0:
result.append(' ')
number_of_spaces -=1
while number_of_octohorpe >= 1:
result.... |
f87485148b631551b008761bcef2d5d3b68a9ef1 | asmikush111/projecttkinter | /validation.py | 1,982 | 4.0625 | 4 | import tkinter # imports Tkinter module
root = tkinter.Tk() # creates a root window to place an entry with validation there
'''
# valid percent substitutions (from the Tk entry man page)
# note: you only have to register the ones you need; this
# example registers them all for illustrative purposes... |
92a85814291d1750b6aba269c09cb2b99fa299f9 | MariusArhaug/FinalStateMachine | /rule.py | 972 | 3.703125 | 4 | """ RULES """
class Rule:
"""
Class for rules to be used for states, signals and actions
"""
def __init__(self, state1, state2, signal, action):
self.state1 = state1
self.state2 = state2
self.signal = signal
self.action = action
def match(self, fsm_state, signal):
... |
c6614a440e29b5c29b1e2931131d2c8208d52636 | william1lai/SPOJ | /ONP.py | 1,288 | 3.671875 | 4 | # let + = 0, - = 1, * = 2, / = 3, ^ = 4
def isOp(ch):
return ch == '+' or ch == '-' or ch == '*' or ch == '/' or ch == '^'
def opPrec(ch):
if ch == '+':
return 0
elif ch == '-':
return 1
elif ch == '*':
return 2
elif ch == '/':
return 3
elif ch == '^':
r... |
baff21b67a80eeac4b67891268476a3f5d69cd65 | maneeshd/algo-ds | /algorithms/prime_factors.py | 1,611 | 4.0625 | 4 | from typing import List
def prime_factors(num: int) -> List[int]:
if num < 2:
return []
if num < 6:
return [num]
p_factors = []
while num % 2 == 0:
p_factors.append(2)
num = num // 2
for i in range(3, int(num ** 0.5) + 1, 2):
while num % i == 0:
... |
ca857be2fab83eac17878a3d5ff51a33b7ac4702 | JackChen207/COMP0034-coursework-1 | /matplotlib_line_graph.py | 654 | 3.828125 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
%matplotlib inline
# Read the data for the population and crime into a data frame skipping the second heading row
data = pd.read_csv('parliamentary-constituency-profiles-data.csv', usecols=["Crime Rate", "F010"], skiprows=[1])
# Cr... |
a65f41d6d1886f2711538a2bd04e30322f3022a9 | taymosier/Python-Practice | /big_diff.py | 718 | 4.09375 | 4 | '''
Given an array length 1 or more of ints, return the
difference between the largest and smallest
values in the array. Note: the built-in min(v1, v2)
and max(v1, v2) functions return the smaller or larger of two values.
'''
def big_diff(nums):
minimum = nums[0]
maximum = nums[0]
for i in ran... |
17312a4c3898c15643b58cec0819caac8d628981 | rab20/Udemy-Blockchain-using-python | /files.py | 497 | 3.984375 | 4 | # Write into a file. Creates the file if non existant
f = open('demo.txt', mode='w')
f.write('Hello from Python!\n')
f.close()
# Append data in the file
f = open('demo.txt', mode='a')
f.write('Hello again!\n')
f.write('-' * 30)
f.close()
# Reads the contents of the file
r = open('demo.txt', mode='r')
fil... |
5ec16a05f554964707b2cfe62474ea55312774b8 | RLeary/projects | /Python/100 challenges/day 8 -26-30/c27 - int to str.py | 312 | 4.34375 | 4 | # Define a function that can convert a integer into a string and print it in
# console.
#
# Hints:
# Use str() to convert a number to string.
def int_to_string(intteger):
return str(intteger)
number = 123
string_from_number = int_to_string(number)
print(string_from_number)
print(string_from_number[2])
|
2ff00e49bdb1c26ae355ee6d2ed30f03023ac8b9 | Niteshrana0007/python | /python_to_JSON.py | 145 | 3.5 | 4 | import json
data = {
"name":"Nitesh",
"marks":[1,2,3,4],
"age":21
}
print(json.dumps(data)) # output is string
|
d78f2a5d6b58c8271f42628a89ec13a1ddd1bed0 | Aasthaengg/IBMdataset | /Python_codes/p03680/s839052949.py | 425 | 3.703125 | 4 | def readinput():
n=int(input())
a=[0]
for _ in range(n):
a.append(int(input()))
return n,a
def main(n,a):
button=[0]*(n+1)
button[1]=1
i=1
count=0
while(True):
i=a[i]
count+=1
if i==2:
return count
if button[i]>0:
retur... |
cdd88f92784c70358044c2a4d2f1e9a762f1110d | florentinolim/pythonestudos | /pythonCursoEmVideo/Exercicios/desafio004.py | 756 | 4.25 | 4 | # Faça um programa que leia algo pelo teclado e mostre na tela o seu tipo primitivo e todas as informações possíves sobre ela
n = input('Digite algo:')
print('O tipo primitivo é ', type(n))
print('O que você digitou só tem espaços? ', n.isspace())
print('O que você digitou é numerico ? ', n.isnumeric())
print('O que v... |
32336f9d5a18fea0199d3cc4fcef1e516b7202c9 | JonathWesley/travelingSalesman | /main.py | 8,466 | 3.734375 | 4 | import numpy as np, random, operator, pandas as pd, matplotlib.pyplot as plt
from City import City
from Fitness import Fitness
# criacao de uma rota
def createRoute(cityList):
# embaralha uma lista com todas as cidades
route = random.sample(cityList, len(cityList))
return route
# cria a populacao inicial
... |
2528512205922c026f1831c6a9aa0e080d38a258 | einik1/pythongames | /list1.py | 811 | 3.609375 | 4 | # -*- coding: utf-8 -*-
def avg_diff(list1, list2):
return float(sum([(list1[i]-list2[i]) for i in range(0, len(list1))]))/len(list1)
f = lambda x: x+2
g = lambda x: abs(x)
def doubleS(str):
return "".join(map(lambda x: x+x, str))
def Sinon(x):
return filter(lambda y: y % 3 == 0, range(1, ... |
efbcba9821722760f57917780a85cbeb45236870 | glifed/Flashbacks_1-5_sem | /4 sem/вычислительные алгоритмы/lab_2.py | 2,011 | 3.578125 | 4 | #Янова Даниэлла ИУ7-43
#Многомерная интерполяция
import numpy as np
import matplotlib.pyplot as plt
from math import sin, cos
def z_f(x, y):
return x**2 + y**2
def y_k(xi, xj, yi, yj):
y = (yi - yj)/(xi - xj)
return y
def interpolation(x, y, n, xx):
y_n=[]
for i in range (n - 1):
f_ij = ... |
f4767670ed3ff7a394c4095011c192f8409a06b0 | simonpaix/Snake-Python-Turtle | /scoreboard.py | 684 | 4.0625 | 4 | import turtle
from turtle import Turtle
class ScoreBoard(Turtle):
def __init__(self):
# class Pen extends Turtle, to make sure it has all the attributes of Turtle we need to initialize Turtle here by calling super.init
# this is necessary because we overrided turtle init method here to write pen init meth... |
a2f99cae189643848065da47cf7609e5bf766951 | CubeSugar/HeadFirstPython | /Day03/print_list_v1.3.py | 478 | 3.859375 | 4 | """
this is a function,
the function :
*print each item of the list
*print every level indent
*print to specify output
v1.3.0
"""
import sys
def print_list(the_list, indent = False, level = 0, output = sys.stdout):
for each_item in the_list:
if isinstance(each_item, list):
print_list(each_item, indent, ... |
9fe87f65ac4b5f7e5a0483e42850dd52f53cff58 | Wendyssh/Wendy-s-python | /D12/D12_liao_breakloop.py | 86 | 3.515625 | 4 | n=1
while n<=100:
if n>10:
break
print(n)
n=n+1
print('end') |
772e9d4ecaea1d441a33afd4e3d5490d48d21fdf | MotazBellah/Code-Challenge | /Algorithms/word_split.py | 1,345 | 4.09375 | 4 | # Create a function called word_split() which takes in a string phrase and a set list_of_words.
# The function will then determine if it is possible to split the string in a way in which
# words can be made from the list of words.
# You can assume the phrase will only contain words found in the dictionary if it is comp... |
3267b4a72603479c9d271441d7aabc5ddd9c2ef5 | shantanu609/Hashing-2 | /Problem3.py | 791 | 3.828125 | 4 | # Time Complexity : O(n)
# Space Complexity : O(52 characters) = O(1)
# Did this code successfully run on Leetcode :
# Any problem you faced while coding this : Yes
# Your code here along with comments explaining your approach
class Solution:
def longestPallindrom(self,string):
if not string or len(string)... |
b9b881b7987a1d5990ca0aaa2d7e8714504a04f3 | glasnak/aoc2017 | /day2.py | 1,266 | 3.6875 | 4 | #!/usr/bin/env python3
"""
--- Day 2: Corruption Checksum ---
"""
input_file = 'input_day2.txt'
def get_input():
with open(input_file, 'r') as f:
return f.readlines()
def parse_input(lines):
""" parse the string into a matrix """
matrix = []
for line in lines:
line_nums = [int(x) f... |
a4854f0100d96b880c655b3e148d9ce7d6869c5a | amydeng2000/InterviewPrep | /BFS/BASICS.py | 2,089 | 3.8125 | 4 | """
- 3 things for graphs: BFS/DFS, Topological Sort, Dikjstra
- Topological sort: directed acyclic graph (DAG) only. In an edge uv, u comes before v in the traversal ordering
"""
from collections import deque
# Iterative Implementation of BFS
# FIRST create the graph (with adjList = [[] for _ in nodes] or using a d... |
ae83aafe048239d8fafae5befa779dee0ec61daf | JakeSeib/Python-Practice | /Isolated problems/array_left_rotation.py | 1,004 | 4.5 | 4 | # A left rotation operation on an array shifts each of the array's elements 1 unit to the left. For example, if 2 left
# rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,2].
#
# Given an array a of n integers and a number, d, perform d left rotations on the array. Return the updated ar... |
9ffe1a5702c5f0df19016ad4796321d73e4a789e | pavi-ninjaac/python | /basic-interaction/dunderMethods_labTest1.py | 1,952 | 3.9375 | 4 | import math
class Lead:
def __init__(self , name , staff_size , estimated_revenue , effort_factor):
self.name = name
self.staff_size = staff_size
self.estimated_revenue = estimated_revenue
self.effort_factor = effort_factor
def __get_digit(self , op):
return len(str(math... |
bb15d5911a95f41a19206e1cc24707e0916b53f3 | sadiqQT/Learn-Python | /Lesson3/3DateTime.py | 518 | 3.671875 | 4 | # to import any library in Python
# one needs to write like
# from *** import ***
# for example
# from datetime import datetime
from datetime import datetime
# print Date and Time
print(datetime.now())
#Make it more readable
print(f"What is the Date and Time now ? = {datetime.now()} " )
# Print individual ... |
058c3ef633960dc41728afa2f010602c89e90bde | qperotti/Cracking-The-Coding-Interview-Python | /Chapter 4 - Trees and Graphs/ex3.py | 959 | 3.90625 | 4 | '''
Exercise 4.3 - List of Depths:
Given a binary tree, design an algorithm which
creates a linked list of all the nodes at each depth.
'''
from collections import deque
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def l... |
c4addf0baad06323e59f0674689c1b7c5b8715b3 | Aasthaengg/IBMdataset | /Python_codes/p02422/s033171556.py | 429 | 3.65625 | 4 | string = input()
for i in range(int(input())):
lst = list(map(str, input().split()))
if lst[0] == "replace":
string = string[:int(lst[1])] + lst[3] + string[int(lst[2])+1:]
if lst[0] == "reverse":
rev_str = str(string[int(lst[1]):int(lst[2])+1])
string = string[:int(lst[1])] + rev_st... |
21543df6921c2046b7924b60af1db37ba58c50cf | paknorton/Bandit | /Bandit/colortest.py | 4,250 | 3.78125 | 4 | #!/usr/bin/python
# Set ANSI Terminal Color and Attributes.
# Original code obtained from: http://code.activestate.com/recipes/574451/
#
from __future__ import (absolute_import, division, print_function)
from sys import stdout
esc = '%s[' % chr(27)
reset = '%s0m' % esc
format_code = '1;%dm'
fgoffset, bgoffset = 30... |
d5835268f5d3de9ceaf8af76e62afe9694d19d23 | shadowsmain/200907 | /200912_homework2.py | 404 | 3.765625 | 4 | my_list = ['v', 'l', 'a', 'd', 'l', 'e', 'n']
my_dict = {'v': 1, 'l': 2, 'a': 3, 'd': 4, 'e': 5, 'n': 6}
print (my_list)
print (my_dict)
print (len(my_list))
print (len(my_dict))
print (len('vl a'))
my_list = ['v', 'l', 'a', 'd', 'l', 'e' 'n']
print('a' in my_list) # True
print('q' in my_list) # ... |
a8b79074a0f7f281769e7436a1ad06c255b980cf | Will-So/dsp | /python/q5_datetime.py | 768 | 4.15625 | 4 | # Hint: use Google to find python function
import arrow
def day_difference(d1, d2, style='MM-DD-YYYY'):
"""Calculates the differences between dates d1 and d2 assuming American date system.
params
---
d1: string of format style
d2: string of format style
style: string dictating how
"""
... |
ff867de67d691780273c629c770b0c8bb6562cab | Rynxiao/python3-learn | /basic/list.py | 679 | 4.125 | 4 | #!/usr/bin/env python3
# list
classmates = ['Michael', 'Bob', 'Tracy']
print(classmates)
# list len
len(classmates)
# 访问
print(classmates[0])
# 反向索引
print(classmates[-1])
# append
classmates.append('Adam')
print(classmates)
# 删除末尾
last = classmates.pop()
print(classmates)
# 删除指定位置的元素
spcial = classmates.pop(1)
p... |
5a92d5463f25712bea0c79a43c296cb615ccc12e | upadhyay-arun98/PythonForME | /Turtle Programs/random_walker.py | 416 | 3.609375 | 4 | import turtle
from random import randint
screen = turtle.Screen()
distance = 50
ttl = turtle.Turtle()
ttl.speed(100)
for i in range(500):
op = ["right", "left", "forward"]
move = op[randint(0,2)]
if move == "forward":
ttl.forward(randint(9, 12))
elif move == "right":
ttl.... |
0ecdf4698785ad6148514a08b1eca46a8923c2f5 | CorSar5/Python-World2 | /exercícios 36-71/ex057.py | 218 | 3.890625 | 4 | s = str(input('Escreva o seu sexo [M/F]: ')).strip()[0]
while s not in 'MmFf':
s = str(input('Dados inválidos. Por favor, informe o seu sexo ')).upper().strip()[0]
print('Sexo {} registrado com sucesso'.format(s)) |
f060a7b08f27e21a82200382811cf4115c477add | leandroaa7/selenium | /sdet-selenium-with-python/class_7/explicitwait.py | 3,399 | 3.609375 | 4 | # -*- coding: utf-8 -*-
# 7/45 Selenium with Python Tutorial 7-WebDriver Explicit wait
'''
Agenda
Waits
-Explicit Wait
Material de apoio
-https://medium.com/@lflucasferreira/entendendo-os-tipos-de-espera-no-selenium-webdriver-2b7adda4db59
-https://medium.com/dev-cave/webdriverwait-fazendo-o-selenium-esperar-a093abeb74... |
53ac712d497650e91cdd1f2adcb36284dfb23744 | PauliKarl/algorithm-track | /movingCount.py | 916 | 3.53125 | 4 | '''
地上有一个m行n列的方格,从坐标 [0,0] 到坐标 [m-1,n-1] 。
一个机器人从坐标 [0, 0] 的格子开始移动,它每次可以向左、右、上、下移动一格(不能移动到方格外),
也不能进入行坐标和列坐标的数位之和大于k的格子。例如,当k为18时,机器人能够进入方格 [35, 37] ,因为3+5+3+7=18。
但它不能进入方格 [35, 38],因为3+5+3+8=19。请问该机器人能够到达多少个格子?
'''
def digitsum(n):
ans = 0
while n:
ans += n % 10
n //= 10
return... |
6b2ceb1c6851551209211d9736e93697ea79e0f2 | ChuseFronden/PythonTasks | /CalculatorwithIf.py | 899 | 4.125 | 4 | print("Calculator")
firstNumber = input("Give the first number:")
firstNumber= int(firstNumber)
secondNumber = input("Give the second number:")
secondNumber = int(secondNumber)
plus = firstNumber + secondNumber
plus = int(plus)
minus = firstNumber - secondNumber
minus = int(minus)
multiplication = firstNumber * secon... |
55b44185a6e2e0891a94d07218ced4188206470d | satanlia/blue-tardis | /prac3_ex4-2.py | 229 | 4.03125 | 4 | #Изменить код так, чтобы в конце каждой буквы добавлялась точка.
s = ['yesterday', 'today', 'tomorrow']
for i in s:
print()
for j in i:
print(j, end=".")
|
bcf250d0c3cda08faa084caebb05a992f2ad9cfe | wildenali/openCV-Basic-with-Python | /43_DetectCorner/43_b_ShiTomasiCorner.py | 1,647 | 3.65625 | 4 |
import cv2
import numpy as np
from matplotlib import pyplot as plt
# https://www.geeksforgeeks.org/circle-detection-using-opencv-python/
'''
Shi-Tomasi Corner Detection was published by J.Shi and C.Tomasi in their paper ‘Good Features to Track‘.
Here the basic intuition is that corners can be detected by looking for... |
109182ac4f732b755c67e7ac49a32008850396fe | jinnovation/JJinProjectEuler | /pe42.py | 1,596 | 3.90625 | 4 | ####PROMPT####
# The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so
# the first ten triangle numbers are:
# 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
# By converting each letter in a word to a number corresponding to its
# alphabetical position and adding these values we form a word value.... |
62449f66361d4c5c57d01bb6975603be19347ade | tangml961025/learn_python | /args_kwargs.py | 438 | 4.25 | 4 | """
args:list
kwargs:dict
经常在装饰器中使用
"""
def test_args_kwargs(arg1, arg2, arg3):
print("arg1:", arg1)
print("arg2:", arg2)
print("arg3:", arg3)
# 首先使用 *args
args = ("two", 3, 5)
test_args_kwargs(*args)
# 现在使用 **kwargs:
kwargs = {"arg3": 3, "arg2": "two", "arg1": 5}
test_args_kwargs(**kwargs)
# 标准参数与*ar... |
dc7d915b87aeed1779e5a0095074238868701201 | avisek-3524/Python- | /gcd.py | 245 | 3.96875 | 4 | ''' write a program to print the gcd of the two numbers'''
a = int(input('enter the first number '))
b = int(input('enter the second number '))
i = 1
while(a >= i and b >= i):
if(a%i==0 and b%i==0):
gcd = i
i = i+1
print( gcd ) |
248f8f6597cff90a3e61f7691400f12d3812f4d4 | 15963064649/-Fluent-Python-NOTE | /第二章/2.1.2计算笛卡尔积.py | 621 | 4.125 | 4 | #此处笛卡尔积的计算实现过程如下:
#加入你需要一个列表,表里是3种不同尺寸的T恤衫,每个尺寸有两个颜色,列表推导写法为:
colors = ['black', 'white']
sizes = ['S', 'M', 'L']
Tshitr = [(color,size) for color in colors for size in sizes] #这里得到的是先以颜色排列,再以尺码排列顺序
print(Tshitr)
#迭代写法为:
for color in colors:
for size in sizes:
print((color,size))
'''
则第一章中的纸牌可以写为:
class... |
f7493df7dd69ca1c08eb5259406270ac30934a8c | vedatonal38/pulling-a-table-from-the-website | /attract_html_table.py | 7,107 | 3.671875 | 4 | import requests as req
import argparse
import pandas as pd
from bs4 import BeautifulSoup as bs
from urllib.parse import urljoin, urlparse
# English : Convert and save HTML tables to CSV or EXCEL Files in Python
# Türkçe : Python'da HTML tablolarını CSV veya EXCEL Dosyalarına Dönüştürüp kaydetme
# kurulum : pi... |
88f677d6bb3856999426b07f1aa413e9bfd5797b | sameertulshyan/python-projects | /daily_weather_update/Send_Html_file.py | 1,321 | 3.609375 | 4 | '''
Created on 10 Jan 2018
@author: Sameer Tulshyan
'''
import smtplib
from email.mime.text import MIMEText
from datetime import datetime
def send_gmail(msg_file):
with open(msg_file, mode='rb') as message: # Open report html file for reading
msg = MIMEText(messag... |
c7320d9ba3f13cb032609a4394f9313831112509 | PandyaDeval/Scooby | /keyphraseid.py | 544 | 3.5 | 4 | import speech_recognition as sr
import speech, time
def nlp_file():
import nlp
r=sr.Recognizer()
keyword='Scooby'
with sr.Microphone() as source:
print('Start talking')
while True:
audio=r.listen(source)
try:
text=r.recognize_google(audio)
if keyword... |
42e18952a35efae6de88e606d3cd7a95b359b744 | OpenImaging/miqa | /samples/convert_miqa_import_csv_format.py | 1,845 | 3.515625 | 4 | import sys
from pathlib import Path
import pandas
for file_name in sys.argv[1:]:
if not Path(file_name).exists():
raise Exception(f"{file_name} does not exist.")
if not file_name.endswith(".csv"):
raise Exception(f"{file_name} is not a CSV file.")
df = pandas.read_csv(file_name)
expect... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.