blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
14cff0973e91bf16ffd036070eb7ebbdb808c5c6 | Robock/project-movies | /media.py | 1,104 | 3.78125 | 4 | import webbrowser
''' This module intitializes instances and plays movie trailers.
In this module, the class Movie has two functions.
The first function, the predefined __init__, initializes the different instances.
The second function, plays movie trailers.'''
class Movie:
def __init__(self, movie_title, movie_story... |
d605e8db427a38d9397eca339b2a99b53188c232 | DrewUniversityCS/CS3 | /database/validators.py | 968 | 3.625 | 4 | """
File Name: Validators
Purpose: Functions for verifying that database data is in an acceptable format.
Comments:
"""
from django.core.exceptions import ValidationError
import django.utils.timezone as timezone
def student_id_validator(sid):
"""
This validator will ensure that the provided id number is
(1... |
9b24af08690a73d719265089cf7a834ddc71045f | lakshyabatman/threading-py | /taxi.py | 1,720 | 3.953125 | 4 | import threading
from queue import Queue
import time
import datetime
f=open("myTaxiLog.txt","w+")
def start_service(number_of_passengers,number_of_cabs):
print_lock = threading.Lock()
def ride(passenger):
time.sleep(2)
with print_lock:
log="Ride : Cab ID:"+str(threading.current_t... |
3ff79f5c6e28114cbd8e7a863aa3de63a0e1b355 | hontrang/hontrang.github.io | /util/indiabix-scrape.py | 2,078 | 3.515625 | 4 | #!/usr/bin/env python
# Author: Aaron Nech
# Description: Scrapes a sub directory of http://www.indiabix.com
# And extracts question and answers in json format.
import os, sys
import argparse
import requests
import json
from selenium import webdriver
from bs4 import BeautifulSoup
# Helper functions
def is_letter... |
eb6ac60c19152d8087b9a6e44609a4aaafb029ee | hjkcmb/cmbwhtensorflowlesson | /Lesson4/homework.py | 2,143 | 3.609375 | 4 | # MNIST分类问题,
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
mnist = input_data.read_data_sets("../MNIST_data/", one_hot=True)
BATCH_SIZE = 100
LR = 0.001
drop_hide = 0.5
x = tf.placeholder(tf.float32, [None, 28 * 28])
y = tf.placeh... |
dc4e80ba79d0e12c126cef843f145c3c52567a60 | xinzhao26/zhaxy187_Assigment_OO_Programming | /user.py | 1,097 | 3.71875 | 4 | #
# File: user.py
# Author: Xin Zhao
# Student Id: 110352998
# Email Id: zhaxy187@mymail.unisa.edu.au
# Date: 22/08/21
# Description: This class represents a user
# This is my own work as defined by the University's
# Academic Misconduct policy.
#This class represents a user
class User:
# User name
__name = ""
#... |
246bef22be101265308f1a1551c04eaeee02dbdf | melvio/python3-examples | /snippets/core_language/files/create_new_file.py | 517 | 3.609375 | 4 | #!/usr/bin/env python3
with open("new_file.txt", "w") as new_file:
new_file.write("hiyaa\nHow ur doin?\n")
print("new_file.closed", new_file.closed) # new_file.closed True
with open("new_file.txt", "r") as created_file:
lines = created_file.readlines()
for line in lines:
print(line, end='')
... |
c7623bbfef7e79177a3a85ddc8294da208c6cdcb | melvio/python3-examples | /snippets/standard_libraries/dataclasseslib/post_init.py | 534 | 3.515625 | 4 | #!/usr/bin/env python3
import dataclasses
@dataclasses.dataclass()
class LabMeasurement:
# https://docs.python.org/3/library/dataclasses.html#post-init-processing
name: str
value: float
unit: str = None
def __post_init__(self):
print(f"__post_init__ {self.name=}")
if self.name == ... |
1000e1488a41b7da18593b3c46b187fcf90e122d | melvio/python3-examples | /snippets/core_language/datastructures/list_appending.py | 274 | 3.84375 | 4 | #!/usr/bin/env python3
numbers = [42, 9001]
letters = "ace"
try:
print(numbers + letters)
except TypeError as err:
print(err) # can only concatenate list (not "str") to list
words = ["ace", "in", "hole"]
print(numbers + words) # [42, 9001, 'ace', 'in', 'hole']
|
0934f65d51ee7edf3174e7a396b462317c6efc0a | melvio/python3-examples | /snippets/popular_libraries/requests/simple_post_request.py | 911 | 3.765625 | 4 | #!/usr/bin/env python3
import requests
from requests import Response
# Using httpbin.org: <https://stackoverflow.com/questions/5725430/http-test-server-accepting-get-post-requests#9770981>
url = "https://httpbin.org/anything"
query_params = dict(amount=5, say="hello")
body_payload = dict(country="US", currency="$")
he... |
77ac30ed9c2fe5ab0e8f29029be42890ea5cb617 | melvio/python3-examples | /snippets/core_language/functions/return_values.py | 295 | 3.78125 | 4 | #!/usr/bin/env python3
def add_to_dict(start_dict: dict):
start_dict["more_wups"] = "Worldcom"
return start_dict
start_value = {"wups": "Theranos"}
print(start_value)
return_value = add_to_dict(start_value)
print(start_value) # start_value has been modified too
print(return_value)
|
5858fa1064dae57b4c94c08ec35868ade063e939 | jpalladino84/PowerballApp | /src/powerball_python/models.py | 1,284 | 3.640625 | 4 | from powerball_python import constants
class InvalidChoiceException(BaseException):
def __init__(self, number):
self.number = number
def __str__(self):
return constants.INVALID_CHOICE_MSG.format(self.number)
class PowerBallEntrant:
"""
Describes a individual that wants to play the ... |
0e8c7b72a7cba01fadb2105dd922cdbf3b243088 | EduardGanea/C | /l1_1_4.py | 99 | 3.5625 | 4 | n=2
m=3
print(n,m,n+m)
print(n,m,n-m)
print(n,m,n*m)
print(n,m,n//m)
print(n,m,n/m)
print(n,m,n%m)
|
90c0fcdefd972257be5bbf183c014e509ebd881a | ricksyuan/read-zhongwen | /pinyin.py | 4,239 | 3.703125 | 4 | import re
def prettify_pinyin(pinyin, delimiter=" "):
"""
Convert pinyin with tone numbers to pinyin with diacritical marks (e.g. ni3 hao3 --> nǐ hǎo).
Input tone mark number must come after the pinyin letters. It cannot be interspersed with letters:
Yes: ni3 hao3. No: ni3 ha3o
Fun... |
412485e1024007908fc7ae3f65bc31897545985b | vaishnavi-gupta-au16/GeeksForGeeks | /Q_Merge Sort.py | 1,565 | 4.125 | 4 | """
Merge Sort
Merge Sort is a Divide and Conquer algorithm. It repeatedly divides the array into two halves and combines them in sorted manner.
Given an array arr[], its starting position l and its ending position r. Merge Sort is achieved using the following algorithm.
MergeSort(arr[], l, r)
If r > l
... |
97688a36659b3c97b78f8ef76410a50d082ffa22 | codeaffect/py_projects | /Regex/MatchingSpecificString/solution.py | 128 | 3.546875 | 4 | import re
rp = r'wikipedia'
s=''
while s!='x':
s = input()
m = re.findall(rp,s)
print('Number of matches:',len(m)) |
c0def40b288146e5da43702ff7d3c29a5dfbd051 | codeaffect/py_projects | /strings/hello.py | 695 | 3.953125 | 4 | print('hello')
first_name=input('whats your first name? ')
last_name=input('whats your last name? ')
print((f'Well hello {first_name} ,{last_name}.Good Day!'))
dob =input('what year were you born? ')
age = 2019 - int(dob)
weight_lbs= input('how much do you weigh (in lbs)? ')
weight_kgs= float(weight_lbs) *.45
fav_color... |
1a1f9168ee23e92f227d6ff49696692440fb4670 | codeaffect/py_projects | /CodeChallenges/StringValidators/answer.py | 301 | 3.59375 | 4 | s = input()
methods = [str.isalnum, str.isalpha, str.isdigit, str.islower, str.isupper]
for res in map(lambda m: any(map(m, s)), methods):
print(res)
# Second method
s = input()
for test in ('isalnum', 'isalpha', 'isdigit', 'islower', 'isupper'):
print(any("c." + test + "()" for c in s))
|
3b87f6a14b8a94660601555012d377a6c3304b04 | codeaffect/py_projects | /CodeChallenges/sWAPcASE/solution.py | 254 | 4.09375 | 4 | def swap_case(phrase):
result = ''
for char in phrase:
if char.isupper():
result = result+char.lower()
else:
result = result+char.upper()
return result
s = input()
result = swap_case(s)
print(result)
|
a5be52dc233541ba6eda4097560a009e8c123227 | codeaffect/py_projects | /CodeChallenges/TextWrap/solution.py | 169 | 3.609375 | 4 | def wrap(s, w):
return "\n".join([s[i:i+w] for i in range(0, len(s), w)])
string, max_width = input(), int(input())
result = wrap(string, max_width)
print(result)
|
6aace1514a01f2872528739ec59bf3212ec53d10 | codeaffect/py_projects | /games/spaceinvaders/game.py | 2,409 | 3.734375 | 4 | import turtle
import os
# global variables
borderspacer = 10
lborder = -300
rborder = 300
tborder = 800
bborder = 0
player_speed = 15
enemy_speed = 2
enemy_step = 20
bullet_speed = 20
bullet_state = "ready" # ready: ready to fire ; fire: bullet is firing
# create background
wn = turtle.Screen()
wn.title("Space Invad... |
d2898ac69327471e890be7c24e5045ca53e24262 | codeaffect/py_projects | /CodeChallenges/practice/pyramidString.py | 71 | 3.5 | 4 | n = int(input())+1
for i in range(1, n):
print(' '*(n-i-1), '#'*i)
|
3db20d9153184142b933e41d26c16d61390ab88e | Floozutter/matherlab | /r_zprime/r_zprime.py | 2,131 | 3.5 | 4 | """
Computes the sample Pearson correlation coefficient (r) and its modified
Fisher z-transformation (z') for a pair of newline-separated text files.
"""
from argparse import ArgumentParser
from math import sqrt, atanh
from typing import List, Tuple
def spcc(x: List[float], y: List[float]) -> float:
"""Returns the ... |
eacaa77f47341af548c121b2b3efcf1e3c7e6f56 | A-meerdervan/RushHourGit | /Daan/Car.py | 411 | 3.765625 | 4 |
class Car:
"""
maintile is the tile with the closest path to the origin
isHorizontal is a booleyan that gives true if Horizontal and is vertical if not Horizontal
length is the length of a car
"""
def __init__(self, mainTile , isHorizontal , length):
# Redirect output to a queue
self.firs... |
1790a082267df080c32f2022c4ee52a8544f4416 | A-meerdervan/RushHourGit | /Daan/stack.py | 352 | 4.0625 | 4 | class Stack:
def __init__(self):
self.items = []
def push(self,item):
self.items.insert(0,item)
def pop(self):
if self.items == []:
print "The stack is empty"
else:
return self.items.pop(0)
stack = Stack()
stack.push(3)
stack.push(4)
print stack.item... |
11c21c978bde75b0371f14b20bbb6f931c9878c4 | A-meerdervan/RushHourGit | /Daan/rushhour_allMoves.py | 3,559 | 3.703125 | 4 | from Car import Car
from CarsList import CarsList
CARS_LIST = CarsList()
WIDTH = 6
HEIGHT = 6
def main():
# TEST met Daans allMoves functie
RedCar = Car(20, True, 2)
Car1 = Car(22, False, 3)
Car2 = Car(9, False, 2)
Car3 = Car(10, True, 2)
CARS_LIST.cars.append(Car1)
CARS_LIST.cars.append(Car2)
CARS_LIST.cars... |
9cadb464d665ebddf21ddc73b136c0cf4026ba11 | chaiwat2021/first_python | /list_add.py | 390 | 4.34375 | 4 | # append to the end of list
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
# insert with index
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
# extend list with values from another list
thislist = ["apple", "banana", "cherry"]
tropical = ["man... |
64f225ef895d09374402f4f4625baeffc13bdd83 | chaiwat2021/first_python | /list.py | 682 | 3.65625 | 4 | # case1
mylist = ["apple", "banana", "cherry"]
print(mylist)
# case2
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
# lenngth
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
# pure data_type
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False,... |
9c99fa836f8afc7fdf6a7407601b4cac5ec17a6e | samgivian/Codeforces-Soloutions | /A. Anton and Polyhedrons/a.py | 282 | 3.796875 | 4 | a =int(input())
m=0
for r in range(0,a):
b=input()
if(b=="Tetrahedron"):
m=m+4
elif(b=="Cube"):
m=m+6
elif(b=="Octahedron"):
m=m+8
elif(b=="Dodecahedron"):
m=m+12
elif(b=="Icosahedron"):
m=m+20
print(m)
|
31a316c0aeed33c8c48d8fc1fabbca2c8111936e | Jaswanth19-596/Calculator-Using-Tkinter | /Calculator.py | 4,302 | 4.21875 | 4 | from tkinter import *
#A simple calculator application
root = Tk()
# This is used when the user presses the = sign , if this is false the ans in the entry is not result
# If it is the result we must remove it while the user is typing another computation
isRes = False
#creating a input field
myInput = Entry(root,b... |
483c1f1a5c4bd0cf1c6386d7860af2f4f20736be | Tuhin-thinks/PAGE-REPLACEMENT-TECHNIQUES | /for_application/optimal_page_replacement_hit_miss_count.py | 3,574 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
This program can calculate the hit and miss % using FIFO method.
Created on Wed Sep 4 16:42:16 2019
@author: tuhin Mitra
"""
# demo = """
# You Can Either enter string like this:
# 1,3,0,3,5,6
# or,
# You can Also Enter like this:
# 130356
# (for better readabili... |
f47e0a404ee9c531f82b657c0cc4ecc987e9279c | 2flcastro/python-exercises | /solutions/2flcastro/intermediate/smallest_common_multiple.py | 2,773 | 4.375 | 4 | # ----------------------------------
# Smallest Commom Multiple
# ----------------------------------
# Find the smallest common multiple of the provided parameters that can be
# evenly divided by both, as well as by all sequential numbers in the range
# between these parameters.
#
# The range will be a list of two numb... |
e5dd7fd413aa887e554db8131c1a3eaf387138af | 2flcastro/python-exercises | /intermediate/finders_keepers.py | 821 | 3.84375 | 4 | # ----------------------------------
# Finders Keepers
# ----------------------------------
# Create a function that looks through a list (first argument) and returns the
# first element in the list that passes a truth test (second argument).
# ----------------------------------
import unittest
def find_element(lst, ... |
23f580da02f03dc0825738e7f5dd4e29b067afff | 2flcastro/python-exercises | /beginner/mutations.py | 1,719 | 3.875 | 4 | # ----------------------------------
# Mutations
# ----------------------------------
# Return true if the string in the first element of the list contains all of
# the letters of the string in the second element of the list.
#
# For example, ["hello", "Hello"] should return True because of the letter in
# the second s... |
f5f41b0c9776dae4fb79b228a0ebb0703ad461f4 | 2flcastro/python-exercises | /beginner/truncate_string.py | 1,770 | 4.0625 | 4 | # ----------------------------------
# Truncate a String
# ----------------------------------
# Truncate a string (first argument) if it is longer than the given maximum
# string length (second argument). Return the truncated string with a "..."
# ending.
#
# Note that inserting the three dots to the end will to their ... |
01552c305741e9f607cce90e6c5a912f5c479077 | 2flcastro/python-exercises | /beginner/factorializeNumber.py | 1,203 | 4 | 4 | # ----------------------------------
# Facorialize A Number
# ----------------------------------
# Return a factorial of the provided ineger.
# If the integer is represented with the letter "n", a
# factorial is the product of all positive integers less
# than or equal to n.
#
# Factorials are often represented with th... |
c253c625f1d74938fc087d2206d75b75c974cd23 | 2flcastro/python-exercises | /beginner/longest_word.py | 1,175 | 4.1875 | 4 | # ----------------------------------
# Find the Longest Word in a String
# ----------------------------------
# Return the length of the longest word in the provided sentence.
#
# Your response should be a number.
# ----------------------------------
import unittest
def find_longest_word(strg):
return len(strg)
... |
cb64405d60c43194cb2fd4455a68a4ec7f4441d0 | 2flcastro/python-exercises | /solutions/2flcastro/beginner/longest_word.py | 2,172 | 4.28125 | 4 | # ----------------------------------
# Find the Longest Word in a String
# ----------------------------------
# Return the length of the longest word in the provided sentence.
#
# Your response should be a number.
# ----------------------------------
import unittest
# using list comprehension and max() built-in funct... |
15804f72a92660a95572c2a1addb4bab69cbf78a | 2flcastro/python-exercises | /intermediate/sum_all_numbers.py | 897 | 3.90625 | 4 | # ----------------------------------
# Sum all Numbers in a Range
# ----------------------------------
# You will recieve a list of two numbers. Return the sum of those two numbers
# and all the numbers between them.
#
# The lowsest number will not always come firt.
# ----------------------------------
import unittest... |
7a8ea8c18c205fc3c8ef0fbafe4f692451458899 | cwavesoftware/python-ppf | /ppf-ex04/even.py | 100 | 4.125 | 4 | print("Enter number?")
num = int(input())
is_even = (num % 2) == 0
print("Number is even: ",is_even) |
244476ab7b61f565a7abd49f01b7d99eb64c1a5f | cwavesoftware/python-ppf | /ppf-ex05/localize.py | 184 | 4 | 4 | lang = input('Enter language? ')
if(lang=="en"):
print("Hello")
elif(lang=="sr"):
print("Zdravo")
elif(lang=="de"):
print("Hallo")
else:
print("Unrecognized language") |
c87d9f875dbfbdf99a82b6c70104563309b5f954 | naumanmustafa16/Coffeemaker | /coffeemaker.py | 14,635 | 4.25 | 4 | # # Write your code here
# print(f'''For 125 cups of coffee you will need:
# {water_requirement} ml of water
# {milk_requirement} ml of milk
#{coffee_requirement} g of coffee beans''')
# water_available = int(input("Write how many ml of water the coffee machine has:\n"))
# with_water_makeable = (water_available//200)
... |
767d1ac413e1c6581a5262e32e8308c8c8b107d4 | CristhianCastillo/course-basic-python | /conditions.py | 375 | 3.9375 | 4 | # Ejercicio uno.
# edad = int(input("Escribe tu edad: "))
# if edad > 17 :
# print('Eres mayor de edad.')
# else :
# print('Eres menor de edad.')
# Ejercicio dos.
number = int(input("Escribe un numero: "))
if number > 5:
print("El numero es mayor a 5.")
elif number == 5:
print("El numero es igual a 5... |
519d29b7c00708ce34f3bcd701b6fdcaed1a1f56 | ads2100/100DaysOfPython | /Week#2/Day6.py | 242 | 3.921875 | 4 | """----------Day6----------"""
#convert to integer
A , B = int(3.9) , int("2")
print(A)
print(B)
#convert to float
C , D = float(3) , float("4.5")
print(C)
print(D)
#convert to string
x , y = str("hi i'm N.O. 1") , str(2.2)
print(x)
print(y)
|
5a55b4a608a8512b528fe6ea53bccca2b13bafba | ads2100/100DaysOfPython | /Week#3/Day16.py | 430 | 4.25 | 4 | """----------Day16----------"""
Tuple1 = ( 'cat' , 5 , 1.9 , 'man' )
print(Tuple1)#print all value
print(Tuple1[0])#print index 0
print(Tuple1[ 1 : 4 ])#print from index 1 to 3
Tuple2 = ( 'Dog' , ) #must use ( , ) if there one value
print(Tuple2)
Tuple3 = ( 'Dog' )#will print as a regular value not tuple
print(Tuple3... |
e86e0c799561266edb464ae5bab7da022a93a667 | ads2100/100DaysOfPython | /Week#4/Day20.py | 494 | 4.09375 | 4 | """----------Day20----------"""
#repeated values can't be print
set1 = { 'Hello' , 'Yes' , 5 , 1 , 'Yes' , 3 , 5 }
print(set1)
#Loop through the set and print the values
set2 = { 'A' , 'B' , 'C' , 'D' }
for x in set2:
print(x)
#Check if value is present in the set
set3 = { 'Hello' , 'Yes' , 5 , 1 , 3 }
print("Yes" ... |
d7450c336fb6108ae173b2df9cb818c095b932f7 | ads2100/100DaysOfPython | /Week#5/Day32&33.py | 130 | 3.75 | 4 | """---------Day32&33----------"""
print('AB')
for x in range(3 , 18 , 2 ):
for y in range(2 , 17 , 2) :
print(x , y)
|
21461cf869ccdbf60483fa57465520315dc12450 | fangfa3/test | /python/BasicAlgorithm/insert_sort.py | 317 | 4.125 | 4 | def insert_sort(array):
length = len(array)
for i in range(1, length):
j = i
while array[j] < array[j - 1] and j > 0:
array[j], array[j-1] = array[j-1], array[j]
j -= 1
if __name__ == '__main__':
A = [2, 4, 5, 8, 1, 9, 7, 6, 3]
insert_sort(A)
print(A) |
313b22a8bb37eb2b86b42ca2a93406ed1955e2a6 | fangfa3/test | /python/BasicAlgorithm/quick_sort.py | 1,083 | 4.03125 | 4 | # 快排
import random
def quick_sort(array, start, end):
if start == end :
return
index = random_Partition(array, start, end)
if index > start:
quick_sort(array, start, index - 1)
if index < end:
quick_sort(array, index + 1, end)
def Partition(array, start, end):
small = st... |
b259a8ef73ccd4182f4193a0e471e0dff97a33a1 | tommasomartini/titanic | /data/integration/parse.py | 5,438 | 3.578125 | 4 | """Collection of functions to parse the website www.encyclopedia-titanica.org
to collect extra data.
"""
import logging
_logger = logging.getLogger(__name__)
_embarking_cities = ['Southampton', 'Cherbourg', 'Queenstown']
def _parse_birth_date(summary_box):
try:
birth_date_span = \
summary_b... |
5b8670231e1a4d44de684b4a0c5d49166114dfb4 | WhiteRobe/Python-alg | /BST.py | 1,857 | 3.671875 | 4 | from structure import TreeNode
class BST:
__root = None
def build(self, tree_list):
for n in tree_list:
self.append(self.__root, n, father=None)
def search(self, key: TreeNode) -> TreeNode:
if self.__root is None:
raise Exception("search:尚未初始化数据")
return s... |
33ae26e2836aa8329fa1e37ed6f983a0b48693f0 | Otis4631/principleOfcompilation | /计科150233李政15111406050/grammar_v1.py | 12,080 | 3.703125 | 4 | import Tokens
from lexer import *
class Symbol:
"""
C文法中的符号标志
"""
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
def match(self, symbol):
if not isinstance(symbol, Symbol):
return False
return (self.name == symbol.name... |
356d286faa926a37bc7f92e4a2edb9778629bbe4 | rafaelvieira96/devessentials | /chalenge2.py | 446 | 4.03125 | 4 | #!/usr/bin/python3
# for em modelo range para delimitar valor
# .format para dar numer exato
# .format(x+1) par somar até o limite do range
soma = 0
for x in range(4):
nota = int(input("Digite nota{}: " .format(x+1)))
soma += nota
media = soma / 4
if media >= 7:
print("Nota {}, aprovado" .format(medi... |
166f72638df619e350bc3763d1082890106a7303 | smysnk/my-grow | /src/lib/redux/compose.py | 820 | 4.1875 | 4 | """
* Composes single-argument functions from right to left. The rightmost
* function can take multiple arguments as it provides the signature for
* the resulting composite function.
*
* @param {...Function} funcs The functions to compose.
* @returns {Function} A function obtained by composing the argument functi... |
cb37df82c4adbfb8943fef5461e8dac00b6b9c93 | jlrcolmenares/Data-Science-Platzi | /src/01-core/01-intro-pensamiento-computacional/12_aproximacion.py | 516 | 3.90625 | 4 | objetivo = int(input('Escoge un número: '))
epsilon = 0.01 #que tan cerca queremos llegar de la respuesta
paso = epsilon**2 #cada cuanto me quiero acercar
respuesta = 0.0
#nuestra respuesta comiensa
while abs(respuesta**2 - objetivo) >= epsilon and respuesta <= objetivo:
print(abs(respuesta**2 - objetivo), respuest... |
f2f48d9fe83918f61428d3200d1435bf13a8ebd7 | jlrcolmenares/Data-Science-Platzi | /src/01-core/01-intro-pensamiento-computacional/11_enumeracion.py | 310 | 4 | 4 | objetivo = int(input('Escoge un entero: ')) #entrada
respuesta = 0 #valor inicial
while respuesta**2 < objetivo:
print(respuesta)
respuesta += 1 #
if respuesta**2 == objetivo:
print(f'la raiz cuadrada de {objetivo} es {respuesta}')
else:
print(f'El objetivo no tiene raiz cuadrar exacta') |
931847d3db85d8964337c1df72fff3f6b070c37d | ilyabihun/homework | /calculator.py | 967 | 4.0625 | 4 | print('Welcome')
while True:
x = float(input('Enter number'))
symbol = input('Enter symbol')
y = float(input('Enter number'))
if symbol == '+':
z = x + y
elif symbol == '-':
z = x - y
elif symbol == '*':
z = x * y
elif symbol == '/':
if y == 0:
pri... |
6cb20abf5cbe2a52b6d490c32a7dd133f62874ab | faculdadeCederj/fundamentosDaProgramacao | /AD2resolucao/Q3.py | 1,130 | 3.546875 | 4 | #SUBPROGRAMAS
def menordist(pontos, centroide):
menorind = 0
for index, ponto in enumerate(pontos):
dist = ((ponto[0]-centroide[0])**2 + (ponto[1]-centroide[1])**2)**(1/2)
if index == 0:
menordist = dist
else:
if dist < menordist:
menorind = index
menordist = dist
stringme... |
e51b0c67211fe5d267d9fed6d37bc0a955c67feb | faculdadeCederj/fundamentosDaProgramacao | /AD2resolucao/Q2.py | 638 | 3.546875 | 4 | #SUBPROGRAMAS
def primo(num):
if num > 1:
for div in range(2, num):
if num % div == 0:
return False
return True
return False
#PROGRAMA PRINCIPAL
arqentradas = input()
arqsaidas = input()
try:
with open(arqentradas, 'r') as entradas:
for linha in entradas:
linhaent = linha.split()... |
059c9316cd8b7ba49264e5647452bdfc7fdbae9a | ranjanyash54/Software-Engineering-ISF341 | /loc/lines_of_code.py | 6,572 | 3.515625 | 4 | import re
import os
import sys
import json
files = []
def get_help():
help = \
"""
LINES OF CODE COUNT
Usage:
python3 lines_of_code <path>
python3 lines_of_code -h | --help
Options:
-h --help Show this screen.
-a --all View supported languages... |
e1d365d32c84361fabcfb9720d806cdfa784e882 | luoyizhi516/Build-CNN-or-LSTM-or-CNNLSTM-with-speech-features | /visualize_features.py | 2,324 | 3.515625 | 4 | '''
This script allows the user to visually explore the parameters for feature extraction. Enter in any wavefile you would like to explore.
'''
import os
from feature_extraction_scripts.feature_extraction_functions import save2png
if __name__=="__main__":
#VARIABLES FOR THE USER TO SET:
#"ca... |
69eea86ec0205b8332e5724e8f8dc1d886ad46b0 | Vedarth/data-structures-and-algos | /Codes in Python/oop/property_decorators.py | 834 | 3.859375 | 4 | class Employee:
def __init__(self, first,last,pay):#Here self is the variable that we will be using inside the class to refer to the instance
self.first = first
self.last = last
@property
def email(self):
return('{}.{}@company.com'.format(self.first.lower(), self.last.lower()))
@property
def full... |
044665142d14acbab93d2ddefdb4bb6822401d37 | Vedarth/data-structures-and-algos | /Codes in Python/oop/class_methods.py | 1,199 | 3.75 | 4 | class Employee:
num_of_emps = 0
raise_amount = 1.04
def __init__(self, first,last,pay):
self.first = first
self.last = last
self.pay = pay
self.email = first.lower() + '.' + last.lower() + '@company.com'
Employee.num_of_emps += 1
def fullname(self):
return '{} {}'.format(self.first,s... |
f99b416c41995986ca188c3ee484be5d55451b3d | alcivar-inca/examen-bimestral-grupo-3 | /Ejercicio4_Examen.py | 697 | 3.765625 | 4 | #EJERCICIO 4
#-- Ingresar una palabra, traducir,
#-- mostrar en pantalla y guardar en un archivo--
import goslate
from tkinter import *
from textblob import TextBlob
#Creamos el archivo
def creartxt():
archivo = open('FrasesT.txt','w')
archivo.close()
#Ingresamos una palabra
app = Tk()
app.title("Aplicacion graf... |
a49c9866c264a5c839d5ef0c944a056045d4839f | sjy9412/startcamp | /day3/fuction.py | 144 | 3.515625 | 4 | def sum(a, b):
# a = 1
# b = 3
return a + b
def hi(name):
return f'{name}, 안녕?'
print(sum(1, 3))
a = hi('안녕')
print(a) |
0f42dfe1e21991c55ca934fd2513991a0e6598f4 | afcarl/Learny-McLearnface | /LearnyMcLearnface/Layers/SigmoidLayer.py | 864 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun May 08 20:14:20 2016
@author: Alexander Weaver
"""
"""
Performs the Sigmoid activation function elementwise on its input array
Sigmoid(x) = 1/(1 + e^(-x))
Forward propagating this object performs the function on an input array and returns the result, saving necessary va... |
ecb16a06a2d6f7ec74a05222c568af9198963d70 | qminhdo/natural-language-processing | /QA/lab/utils.py | 3,760 | 3.734375 | 4 | import os
import pickle
def read_file(filename, rp):
"""
:argument:
:param filename: A string which represents the raw data file, in properties.conf,
used for the process (experiment).
:param rp: Absolute path of the root directory of the project
# Note: Fil... |
ec80afb98759a842812890cfe4f958e111f73b18 | XuanYang-cn/leetcode | /series/buy_and_sell_stock_seires.py | 4,630 | 3.703125 | 4 | """
Best Time To Buy And Sell Stock Series
"""
__author__ = 'Yang Xuan (jumpthepig@gmail.com)'
class Solution:
"""
121. Best Time To Buy And Sell Stock 买卖股票的最佳时机
Difficulty: Easy
Description: 只允许完成一笔交易,即买入和卖出一支股票
"""
@classmethod
def brute_force(self, prices: list) -> int:
'''bru... |
07f9e69e7362590bda7649b34d99a415e60af8c1 | vijayraikar1999/Object-Oriented-Programming | /App-2-Flatmates-Bill/flat.py | 647 | 3.875 | 4 | class Bill:
"""
Object that contains data about a bill, such as total amount and period of the bill.
"""
def __init__(self, amount, period):
self.amount = amount
self.period = period
class Flatmate:
"""
Creates a flatmate person who lives in the flat and pays the share of the ... |
80c7a5e3c64f31e504c793b59951260636c65d17 | mike-something/samples | /movies/movies_0.py | 974 | 4.3125 | 4 | # https://namingconvention.org/python/
#
# define variables for the cost of tickets
#
# we try and use names for variables which are clear and memorable. Its
# good to prefer longer names which are clearer - in a large program this
# can really matter
#
adult_ticket_cost = 18
child_ticket_cost = 10
print('... |
4d5d8a7abc2720b165b2fcde2dba1863a0f9a701 | carlos-paezf/Snippets_MassCode | /python/shuffle.py | 544 | 4.0625 | 4 | #:information_source: The same algorithm is already implemented
#via random.shuffle.
#Randomizes the order of the values of an list, returning a new list.
#Uses the Fisher-Yates algorithm to reorder the elements of the list.
from copy import deepcopy
from random import randint
def shuffle(lst):
temp_lst = deepco... |
76db9c3360d671f7461297a63475063908e33df9 | carlos-paezf/Snippets_MassCode | /python/factorial.py | 472 | 4.5 | 4 | #Calculates the factorial of a number.
#Use recursion. If num is less than or equal to 1, return 1.
#Otherwise, return the product of num and the factorial of num - 1.
#Throws an exception if num is a negative or a floating point number.
def factorial(num):
if not ((num >= 0) & (num % 1 == 0)):
raise Excep... |
c8f0da7555edde737b7f5e8ad697305b1087079c | carlos-paezf/Snippets_MassCode | /python/keys_only.py | 714 | 4.3125 | 4 | #Function which accepts a dictionary of key value pairs and returns
#a new flat list of only the keys.
#Uses the .items() function with a for loop on the dictionary to
#track both the key and value and returns a new list by appending
#the keys to it. Best used on 1 level-deep key:value pair
#dictionaries (a flat dictio... |
e60a58f1a47e3b0e6ef457eb95ae2c0d0627fefb | surajwarbhe/OS_menu_driven_code | /runcode.py | 11,291 | 3.734375 | 4 | #importing applications in Windows
import os
import pyttsx3
import calender
import date
username="Suraj"
secret_code="17042001"
flag=1
while (flag==1):
print(" Enter your Username : ")
pyttsx3.speak("Enter your Username")
u=input()
print("Enter your Secret code : ")
pyttsx3.speak("Enter your Secret code ")
... |
0b65e6a288f16ba57a6bad261d749c1756febf0a | shahirahmed/testrepo | /test.py | 413 | 3.640625 | 4 | daily_balances=[107.92, 108.67, 109.86, 110.15]
show_balances(daily_balances)
def show_balances(daily_balances):
# do not include -1 because that slice will only have 1 balance, yesterday
x=len(daily_balances)
for day in range(x-3,x-1):
balance_slice = daily_balances[day : day + 2]
# use positive number for pri... |
33eaf8b6efc8f4c0321c84cd6670ced54511a2c5 | glibesyck/Queue_Stack | /queue_to_stack.py | 729 | 4.09375 | 4 | """
Queue to stack converter.
"""
from arrayqueue import ArrayQueue
from arraystack import ArrayStack
def queue_to_stack(queue):
"""
Converts queue to stack.
"""
temp_queue = ArrayQueue()
temp_stack = ArrayStack() #elements are in reversed order
result_stack = ArrayStack()
while not queue... |
fb753536c08881d522a6d65fa8d7e5a3da5a127b | philtap/Yelp_reviews_analysis | /Review_Preprocessing/Review_Preprocess.py | 8,549 | 3.734375 | 4 | ########################################################################################################################
# Yelp - review text preprocessing
#
# Review_Preprocess.py
#
# This python program takes as input a csv file containing reviews and applies preprocessing to the review text
# using Natural Language... |
56f8f9eb11022cce409c96cabf50ecb13273e7df | HaoyiZhao/Text-chat-bot | /word_count.py | 1,116 | 4.34375 | 4 | #!/usr/bin/python
import sys
import os.path
# check if correct number of arguments
if len(sys.argv)!=2:
print "Invalid number of arguments, please only enter only one text file name as the command line argument"
sys.exit()
# check if file exists
if os.path.isfile(sys.argv[1]):
file=open(sys.argv[1], "r+")
wordFreq... |
c98d0137016900b743cf3683dccad0d8f342063c | iamprogrammer-study/codinginterview | /009_invert_binary_tree/javawork_invert_binary_tree.py | 1,058 | 3.859375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeN... |
fa004396f2b49aa0677b78c61708a790e4f36cc7 | sarank21/SummerSchool-Assignment | /Abhinav_AE20B002/Class.py | 444 | 3.640625 | 4 | class finder
dict={}
count=1
def checktarget(self,m,tar,arr)
for i in range (0,m)
for j in range (0,m)
if arr(i)+arr(j)==tar
dict.update({count:[i j]})
count++
arr=[]
obj=finder()
n=int(input("Enter number of elements\n"))
for i in range (0,n)
x=int(inpu... |
c6c066383c6d2fc587e3c2bf5d26ee36c060e288 | sarank21/SummerSchool-Assignment | /SaiShashankGP_EE20B040/Assignment1Q2.py | 1,483 | 4.25 | 4 | '''
Author: Sai Shashank GP
Date last modified: 07-07-2021
Purpose: To find a pair of elements (indices of the two numbers) from a given array whose sum equals a specific target number.
Sample input: 10 20 10 40 50 60 70
Sample ouput: {1: [0, 3], 2: [2, 3], 3: [3, 0], 4: [3, 2]}
'''
# importing useful libraries
impor... |
11e4324bf7174179c032c239d3b19af379dd871a | Iaraseverino/my-first-repo | /Projects/exercise.py | 397 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 13 22:05:34 2020
@author: Iari Severino
"""
def is_even():
number = input("type a number: ")
if int(number) % 2 == 0:
print('true')
else: print('False')
is_even()
#%%
def is_odd():
number = input("type a number: ")
if int... |
d48b4613d4a2da0cea41b55ed90fbc18a52f9773 | mburban/HomeWork5 | /homework5_3.py | 441 | 3.5625 | 4 | # Напечатать таблицу Пифагора заданной конфигурации.
# Образец: https://cdn.lifehacker.ru/wp-content/uploads/2017/01/700_1485755264.jpg
i = 0
while i <= 10:
j = 0
while j <= 10:
if i+j == 0:
print('\t', end='')
elif i*j == 0:
print('\t', i+j, end='')
else:
... |
a9fa08ee16eaed9377dd335d028fbf31372242d6 | BonfireHobo/Game_of_life | /main.py | 571 | 3.828125 | 4 | from game_board import GameBoard
def main():
# Game Info // Create game
game = GameBoard(15, 15) # Row, column
exit_game = False
# Game loop
while not exit_game:
# Print game board and info
game.draw_board()
print(game)
# Update or quit
_... |
6526e0df708d3dc016f0761493b20eceee9e5f59 | driver47/pythonbasic | /1.fibonacci.py | 185 | 3.625 | 4 | #hello first step
a , b = 0 , 1
while a < 1000:
print (a, end=(',')) # end evita el salto de linea y me permite una cadena diferente en este caso agrego la ,
a, b = b, a + b |
434368c1a1c1a36ce9a8d1edd9c79945ee2996a8 | aricannon21/dict_practice | /dict_practice.py | 925 | 4.09375 | 4 | def main():
temp_dict = {}
# print(type(temp_dict))
temp_dict['AU'] = 'Washington, DC'
print(temp_dict)
temp_dict['AU'] = 'Paris'
print(temp_dict)
del temp_dict['AU']
print(temp_dict)
if __name__ == '__main__':
main()
#_______________________________
def main():
spring_2020_list = ['Computer Science', 'Sp... |
266d32d81be71f6487fc28eaed4547eabc0c7370 | anikethanaga/Academics | /sem5/labs/NTC/NTC_Lab3/171IT208_IT462_P3.py | 2,946 | 3.578125 | 4 | import random
import math
def file_ops(lines):
f = open("171IT208_IT462_P3_Output.txt", "a")
for line in lines:
print(line)
f.write(line + '\n')
f.write('\n')
f.close()
return
def prime_factorize(n):
factors = []
if (n % 2 == 0):
factors.append(2)
while (n % 2 =... |
cbcc6ac96dd9c4360e782350c3b15a8ad8081515 | amingZhang/LearnPython3ByLiaoxuefeng | /024Class.py | 2,709 | 3.59375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# __author__ = 'zhang.c.m'
class Student(object):
"student document"
# 只有下面槽中允许的属性和方法才可以被绑定到类的实例中
__slots__ = ('__name', '__score', 'age', 'gender', 'set_age', 'set_gender')
def __init__(self, name, score):
self.__name = name # __两个下划线表示privat... |
13b0ace8af3778ef0c6ebb9b075091a8d9ccd06d | amingZhang/LearnPython3ByLiaoxuefeng | /007Quadratic.py | 1,014 | 3.65625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# __author__ = 'zhang.c.m'
import math
def checking_input_for_quadratic(a, b, c):
tuple_input = (a, b, c)
for x in tuple_input:
if not isinstance(x, (int, float)):
print('请使用int型或float型')
return False
if a == 0:
prin... |
d5131ecef9b8ab0918033d2a66a4e21ff329dd39 | NinjaOnRails/fillgaps | /fillGaps.py | 916 | 4.15625 | 4 | #! /usr/bin/env python3
# fillGaps - Finds all files with a given prefix in a folder,
# locates any gaps in the numbering and renames them to close the gap.
import shutil, os, re
folder = input("Enter path to the folder containing your files: ")
prefix = input("Enter prefix: ")
def fillGaps(folder, prefix):
reg... |
839a7cfc63d5d49421c7ec22573b3b5161ba2f63 | christodragnev/unit2 | /fortuneTeller.py | 772 | 3.765625 | 4 | #Christo Dragnev
#1/29/18
#fortuneTeller.py
color = str(input('Pick red or blue: '))
num = int(input('Pick a number from 1-4: '))
if color == 'red' and num == 1:
print('You will be attacked by a bear')
elif color == 'red' and num == 2:
print('You will be attacked by a shark')
elif color == 'red' and num == 3:... |
ddb8ca81f655ecb94bd530b7196ea1fcd756832f | nicolasarcas/uri_py | /uri_1096.py | 118 | 3.53125 | 4 | i=1
j=7
while i <= 9:
for y in range(3):
print('I='+str(i)+' J='+str(j))
j-=1
i += 2
j = 7 |
305e157abb2e5712b700a39572bd164b731f68dd | enriqueee99/learning_python | /program.py | 5,860 | 3.9375 | 4 | # PI = 3.1415 #constante todo mayusculas
# MY_NAME = 'Anthony'
# MY_NAME = 'Enriqueee'
# print(PI, MY_NAME)
#---------------------------------------------------------
# decima = 100
# print(decima) #100
# print(type('hello')) #class str
# print('bye' + ' world') #bye world
# print(type(8.7)) #float
# a, b = 10, 21... |
23152386219203cd737c4dde47f9822c410ba181 | enriqueee99/learning_python | /ejercicio_16.1.py | 466 | 4.25 | 4 | personas = {}
for x in range(3):
numero = int(input('Ingrese el numero de la persona: '))
nombre = input('Ingrese el nombre de la persona: ')
personas[numero] = nombre
print('Listado completo de las personas: ')
for numero in personas:
print(numero, personas[numero])
num_consulta = int(input('¿Qué num... |
a7aff197a21019a5e75502ad3e7de79e08f80465 | jesusbibieca/rock-paper-scissors | /piedra_papel_tijeras.py | 2,820 | 4.4375 | 4 | ##Rock, paper o scissors##
#Written by Jesus Bibieca on 6/21/2017...
import random # I import the necessary library
import time #This will import the module time to be able to wait
#chose = "" #Initializing variables
def computer(): #This function will get a rand value between 1-99 and depending on the num... |
901db24c85425b19560080eedd6e7d9e2ab48149 | Akus0ni/bug-free-fiesta | /Return_functions-ex21.py | 607 | 4.03125 | 4 | def add(a,b):
print "Adding %d + %d" %(a,b)
return a+b
def substract(a,b):
print "Substracting %d - %d" %(a,b)
return a-b
def multiply(a,b):
print "Multi %d * %d" %(a,b)
return a*b
def divide(a,b):
print "Divide %d / %d" %(a,b)
return a/b
age = add(30,5)
height = substract(77,3)
weight = multiply(37,2)
... |
13c728affd7e5939a50aa5001c77f8bf25ee089c | FadilKarajic/fahrenheitToCelsius | /temp_converter.py | 653 | 4.4375 | 4 | #Program converts the temperature from Ferenheit to Celsius
def getInput():
#get input
tempInCAsString = input('Enter the temperature in Ferenheit: ')
tempInF = int( tempInCAsString )
return tempInF
def convertTemp(tempInF):
#temperature conversion formula
tempInC = (tempInF - 32) *... |
273f798d759f25e69cfe21edcad3418d66ffd0aa | Victor094/edsaprojrecsort | /edsaprojrecsort/recursion.py | 1,020 | 4.46875 | 4 | def sum_array(array):
'''Return sum of all items in array'''
sum1 = 0
for item in array:
sum1 = sum1 + item # adding every item to sum1
return sum1 # returning total sum1
def fibonacci(number):
"""
Calculate nth term in fibonacci sequence
Args:
n (int): nth term in fib... |
4baf62770e812c78ab7af4730e6128170e7eef15 | Rekid46/Python-Games | /guess_the_number/app.py | 1,010 | 4 | 4 | import random
from art import logo
number=random.randint(1,100)
print(logo)
def game(number):
game_over=False
diff=input("Choose a difficulty. Type 'easy' or 'hard': ")
if diff=='easy':
lives=10
else:
lives=5
while not game_over:
print(f"You have {lives} attempts left to gue... |
c1ea1eede64d04257cd5ba8bde4aea1601044136 | Rekid46/Python-Games | /Calculator/app.py | 1,076 | 4.1875 | 4 | from art import logo
def add(a,b):
return(a+b)
def subtract(a,b):
return(a-b)
def multiply(a,b):
return(a*b)
def divide(a,b):
return(a/b)
operations = {
"+": add,
"-": subtract,
"*": multiply,
"/": divide
}
def calculator():
print(logo)
n1=float(input("Enter first number: "))
n2=floa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.