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 |
|---|---|---|---|---|---|---|
b2bb3426de3c31e3964fe45056dbd2eed81e8961 | Mhd-Shuvo/python_practice | /D8P2.py | 378 | 3.890625 | 4 | employee = ['a','t','s','n']
employee_name_list = ['avee','tamzeed','shuvo','nobel']
employee= input()
if (employee == 'a'):
print (employee_name_list[0])
elif (employee == 't'):
print (employee_name_list[1])
elif (employee == 's'):
print (employee_name_list[2])
elif (employee == 'n'):
print (employ... |
f41f461ab2fe28e586935dd265e9056f79d4abb6 | Kingslayer124856/CP1404_Practical | /Practical_02/files.py | 103 | 4.1875 | 4 |
open('Name1.txt', 'w')
getname= input("Whats your name?:" )
print("Your name is {}".format(getname))
|
306ae26dcf5c1b13a2df93581f4025d2659a8264 | kartik-soni1707/Python-Practicals | /Exception Handling .py | 377 | 3.625 | 4 | try:#try something
a = int(input('Enter Val1:'))
b = int(input('Enter Val2:'))
print(a/b)
except ZeroDivisionError:
print('No div by 0!!')
except ValueError:
print('Enter numbers!!')
except Exception as err:#handle errors here
print('Something wicked happend!!:',err)
finally:#this ... |
ebbaa0274821801c9cddb364e312b021b3345755 | jmendiola84/python-challenge | /PyPoll/main.py | 2,737 | 3.921875 | 4 | #Import libraries
import os
import csv
#Create a file to store elections results
file=open("Elections Results.txt","w")
#Declare variables
totalVotes=0
#Select only CSV files required into the directory
for filename in os.listdir("Data"):
if filename.endswith(".csv"):
#CSVS files path
electionCSV =... |
e7f41781103a7cc0c785e38324865a2803ac9826 | rezaBarzgar/puzzle-15 | /Utils.py | 292 | 3.625 | 4 | def is_in_closed_list(closed, node):
for item in closed:
if item == node:
return True
return False
def standard_printer(state):
x = ''
for i in state:
for j in i:
x += str(j)
x += ','
x = x[0:len(x) - 1]
return x
|
a226387d4372d44bf06172cea4b17cec72dbda31 | nimirum/infantes | /wrangling/data_analysis.py | 958 | 3.5 | 4 |
import pandas as pd
##
fertility_rate = pd.read_csv("../data/kokonaishedelmallisyys_2000_2016.csv", encoding='utf8', sep=';')
births = pd.read_csv("../data/syntyneet_lapset_1987_2016.csv", encoding='utf8', sep=';')
#print(fertility_rate.head())
#print(births.head())
#print(births.columns.values)
births2016col = '20... |
e5aa52deaa2bfab2746cd5bc16053f3ff0f0dac5 | jmr172/Door-Detector | /Door_Detector.py | 1,739 | 3.515625 | 4 | '''
Created By: James Rogers
Last Modified By: James Rogers
Last Modified On: 01/06/2018
Purpose: To detect if a door is open and send an email alert
'''
import sys
import RPi.GPIO as GPIO
import time
import smtplib
if (len(sys.argv) != 2 or sys.argv[1] == "-h"):
print("Usage: python3 Door_... |
acd8d96bd9fc618568a532e0cead4ded9514f369 | abhiinavkumarr/Website-Blocker | /websiteblocker[1].py | 1,035 | 3.5 | 4 | import time
from datetime import datetime as dt
redirect="127.0.0.1"
websites=["www.youtube.com","youtube.com", "www.facebook.com", "facebook.com"]
while True:
if dt(dt.now().year,dt.now().month,dt.now().day,9,50) < dt.now() < dt(dt.now().year,dt.now().month,dt.now().day,9,51):
print ("WORKI... |
1e06c383366bae1ff2c85be0d920e0d835618fbe | lordievader/advent_of_code | /2018/python/day_01/part_1.py | 569 | 3.765625 | 4 | import numpy
def to_int(numbers):
"""Converts the input strings to integers.
:param numbers: list of frequencies
:type numbers: list of strings
:return: list of integers
"""
return [int(number) for number in numbers]
def sum_freq(numbers):
"""Sums frequencies.
:params numbers: list... |
c816bef62d308421dfc4b9d99a1ec53b0f5d80d1 | lordievader/advent_of_code | /2018/python/day_01/part_2.py | 713 | 3.671875 | 4 | import part_1
class Frequency():
def __init__(self):
self.current_frequency = 0
self.past_freqencies = []
def new_frequency(self, frequency):
self.past_freqencies.append(self.current_frequency)
self.current_frequency += frequency
def is_current_duplicate(self):
ret... |
256fa0a650247f8a66f2ce7fe90138a99863b3bd | ericgorday/OpenCVTests | /Extract_ROI.py | 458 | 3.5 | 4 | import cv2
import numpy as py
if __name__ == '__main__':
# program displays a picture and allows the user to manually select the roi using a rectangle created by the mouse input
image = cv2.imread("test_pictures/rainbow.png")
fromCenter = False
showCrossHair = False
(x,y,w,h) = cv2.selectROI("Image", image, from... |
41d226b57b7eb95ccaffea82fec0dabcbb97d45e | singhsukhendra/Data-Structures-and-algorithms-in-Python | /Chapter#07/LinkedQueue_subClass_of_DoublyLinkedBase.py | 1,193 | 3.5625 | 4 | from _DoublyLinkedBase import _DoublyLinkedBase, Empty
class LinkedDeque(_DoublyLinkedBase): # LinkedDeque is a subclass of _DoublyLinkedBase
""" Double-ended queue implementation based on a doubly linked list
"""
def first(self):
if self.is_empty():
raise Empty('The empty')
re... |
be817e3fc49c18c648877ca872c6e3b186a93849 | singhsukhendra/Data-Structures-and-algorithms-in-Python | /Chapter#07/ex_R_7_22.py | 10,003 | 3.578125 | 4 | class _DoublyLinkedBase:
""" A base class providing a doubly linked list representation."""
class _Node:
__slots__ = '_element' , '_prev' , '_next' # streamline memory
def __init__(self, element, prev, next): # initialize node’s fields
self._element = element # user’s element
... |
f6f37685f81b0fbfb3eef7f8ec868c22c44f8f1d | singhsukhendra/Data-Structures-and-algorithms-in-Python | /Chapter#06/Stack.py | 1,701 | 3.859375 | 4 | class Empty(Exception):
""" Error attempting to access element from empty container.
Note that Empty is a subclass of python's builtin Exception class"""
pass
class ArrayStack:
""" This class implements stack using Python list as an Adapter Pattern.
Methods to implement for realizing Stack... |
9d9206ef57e6dfb7444b1eb1391f5d705fb3c929 | singhsukhendra/Data-Structures-and-algorithms-in-Python | /Chapter#02/ex_R_2_9.py | 2,612 | 4.34375 | 4 | class Vector:
""" Represent a vector in a multidimensional space."""
def __init__(self, d):
""" Create d-dimensional vector of zeros. """
self._coords = [0] * d
def __len__(self): # This special method allows finding length of class instance using len(inst) style .
""" Return the ... |
93ca2c74cec24b0fb12187f9a41fcfb3993ef611 | Karmini/MPC | /root.py | 968 | 3.6875 | 4 | #Approximation numérique d'une racine avec la méthode de Heron
c = float(input("Racine à calculer : "))
while c <= 0:
c = float(input("Racine à calculer : "))
x0 = c
epsilon = 10**(-10)
Nitermax = 100
def racine(x0, epsilon, Nitermax):
for m in (1,8):
n = Nitermax
e = epsilon... |
31913cba8116e128747fd52efe6a37eedcc65baa | nessalc/AdventOfCode | /advent2022/cheat09.py | 1,859 | 3.640625 | 4 | # AoC day 9
class Knot:
def __init__(self):
self.x = 0
self.y = 0
@property
def pos(self):
return self.x, self.y
class Head(Knot):
def step(self, direction):
# move 1 step in the direction
match direction:
case 'U':
self.y += 1
... |
bf0813474bb4780be642128a9b0eb65805c61149 | nessalc/AdventOfCode | /advent2022/day13.py | 1,403 | 3.71875 | 4 | from itertools import zip_longest
from functools import cmp_to_key
def compare(left:int|list,right:int|list)->bool:
if isinstance(left,int) and isinstance(right,int):
#print(f'int v int\n{left} v {right}')
return -1 if left<right else 1
elif isinstance(left,list) and isinstance(right,list):
... |
57073142aa6f15d84f7476e22e6281cca69c9b8c | nessalc/AdventOfCode | /advent2022/day02.py | 1,539 | 3.8125 | 4 | def score_1(play):
# A, X is Rock
# B, Y is Paper
# C, Z is Scissors
# Rock is 1, Paper is 2, Scissors is 3
# Win is 6, Draw is 3, Lose is 0
a,b=play
if a=='A':
if b=='X':
return 1+3
elif b=='Y':
return 2+6
elif b=='Z':
return 3+0
... |
40c50edae79808a40a98d5538f1fba55bdb58938 | fredzhangziji/myPython100Days | /Day9_Class_Object_Advanced/decorators.py | 2,312 | 4.25 | 4 | '''
python内置的 @property装饰器 (Decorators)
之前我们讨论过Python中属性和方法访问权限的问题,虽然我们不建议将属性设置为私有的,
但是如果直接将属性暴露给外界也是有问题的,比如我们没有办法检查赋给属性的值是否有效。
我们之前的建议是将属性命名以单下划线开头,通过这种方式来暗示属性是受保护的,不建议
外界直接访问,那么如果想访问属性可以通过属性的getter(访问器)和setter(修改器)
方法进行对应的操作。如果要做到这点,就可以考虑使用@property包装器来包装getter和
setter方法,使得对属性的访问既安全又方便,代码如下所示。
'''
class Person(objec... |
381fe255c58115bb31ccba6a94d3f69216367d9f | fredzhangziji/myPython100Days | /Day3_BranchStructure/practice1_cmToinch.py | 740 | 4.5 | 4 | '''
Convert between cm and inch
12/17/2019
written by Fred Zhang
'''
while True:
print("\n\n-------Welcome to cm/inch Converter Version 1.0-------")
print("Enter 'cm' for converting inch to cm;")
print("Enter 'inch for converting cm to inch;")
print("Enter 'e' for exiting the program.")
pri... |
4db295d5fb56f4a6779bffc189e483f6fe58dfb0 | fredzhangziji/myPython100Days | /Day3_BranchStructure/practice2_pointToGrade.py | 678 | 4.15625 | 4 | '''
Convert 100-point scale to grade scale
12/17/2019
written by Fred Zhang
'''
print('\n\nYo this is a grade converter you sucker!\n')
point = int(input('put in your stupid-ass points here: '))
print()
if point <= 100 and point >= 90:
print('You got a fucking A. Greate fucking job!')
elif point < 90 and ... |
28df5a8ca0c2ed5bf2bdbc571844a352d9266fd8 | fredzhangziji/myPython100Days | /Day2_Variable_Operator/practice1_FahrenheitToCelsius.py | 1,227 | 4.53125 | 5 | '''
A simple program to convert between Fahrenheit and Celsius degrees.
12/17/2019
written by Fred Zhang
'''
while True:
print('**************************************************')
print('**************************************************')
print('Welcome to Fahrenheit and Celsius degree converter'... |
44a5559b8edfa07ebfd410e6cc58f8c0b4232853 | languoqing/leetcode | /findminnum.py | 1,099 | 4 | 4 | '''
给定一个未排序的整数数组,找出其中没有出现的最小的正整数
'''
def findMinNum(l):
if l == []:
return 1
sortlist = sorted(l)
zlist = []
for x in sortlist:
if x > 0 and x not in zlist:
zlist.append(x)
if zlist == []:
return 1
flag = 0
for x in range(len(zlist)):
if zlist[x] =... |
ba262e68e8d56f0ba47dc88aaba1fe3a37ed4ecd | languoqing/leetcode | /strStr.py | 655 | 3.953125 | 4 | #-*- coding:utf-8 -*-
"""
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,
则返回 -1。
"""
def strStr(Astr,Bstr):
'''Astr 需要包含Bstr,不存在返回-1'''
if Astr == Bstr:
return 1
elif Astr == '' or Bstr == '':
return -1
elif (Astr and Bstr) or (Astr != '' and Bstr !=... |
54168dc279979bd68c78961eef50f9c229f6bb71 | languoqing/leetcode | /singleNumber.py | 637 | 3.703125 | 4 | """
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现了三次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
"""
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dp = {}
for i in range(len(nums)):
dp[i] = nums[i]
... |
6ff06eb58bc0deca7987c036855822e85e368745 | shivamsood/Python | /factorial.py | 267 | 4.46875 | 4 | #Code to calculate Factorial of the user entered integer
factorial_input = input("Please enter the number to calculate Factorial\n\n")
output = 1
while factorial_input >= 1:
output *= factorial_input
factorial_input -=1
print "The Factorial is {}".format(output) |
d6e5c2d80d2dfed67435368416cde5e5d312701e | Auskas/SmartMirror | /clockwidget.py | 6,112 | 3.609375 | 4 | #!/usr/bin/python3
# clockwidget.py - creates a clock and a calendar widgets and updates the current time and date.
from tkinter import *
import datetime
import time
import logging
class Clock:
def __init__(self, frame, database, voiceAssistant, gesturesAssistant):
self.logger = logging.getLogger('Gesell... |
311ef302efdb52f3977213d7fb2a1fbf69c48e32 | wpresti/PythonProjects | /Pandas/obesity.py | 1,788 | 3.5 | 4 | #uncomment plt.show() if you want to see plot in GUI
import pandas as pd
import matplotlib.pyplot as plt
#import data
data = pd.ExcelFile("Obes-phys-acti-diet-eng-2014-tab.xls")
print("The sheet names are: ", data.sheet_names)
#define columns to be read in (note-- year doens't have a header)
#so we make one
columns1 ... |
4cf8a2f6e9340e5f86b24b534546054b939cca81 | wpresti/PythonProjects | /Plotting/list_comp.py | 629 | 3.984375 | 4 | import numpy as np
x = [5,10,15,20,25]
# declare y as an empty list
y = []
#old fashined way below
for counter in x:
y.append(counter / 5)
print("\nOld fashioned way: x = {} y = {} \n".format(x, y))
#new way using List comprehensions
#[ <do something> for value in list]
#divide x by 5
z = [n/5 for n in x] #[]... |
90f7000a8ddea261416cf1b305aee9f2c736993b | jorszs/computacion_grafica | /escalar_triangulo.py | 3,096 | 3.8125 | 4 | import pygame
from fractions import Fraction
'''escalar triangulo
1.dibujar triangulo con clicks(tres clicks en la pantalla)
2.flecha hacia arriba para escalar el doble del triangulo
3.flecha hacia abajo para escalar en 0.5 el triangulo
'''
#funciones--------
#trasforma un punto de cartesiano a pantalla
def tr... |
e99182b5e3949f463dd8b58f2052a9454465e1c9 | Akvanvig/Python-prosjekt | /Sorteringsalgoritmer/Mergesort.py | 1,704 | 3.828125 | 4 | #Mottar ei liste, og deler denne opp i to tilnærmet like store lister
def splittListe(l):
midtpunkt = len(l) // 2
l1 = l[:midtpunkt]
l2 = l[midtpunkt:]
return l1, l2
#Slår sammen listene sortert
def slaaSammenSortert(l1, l2):
#Hvis ei av listene er tomme
if len(l1) == 0:
return l2
e... |
94d927717a335701f06a6744353859dd185bc9e5 | Akvanvig/Python-prosjekt | /Sorteringsalgoritmer/testprogram.py | 786 | 3.5625 | 4 | import time
import Bubblesort as b, Selectionsort as s, Insertionsort as i, Mergesort as m
liste = [0, 5, 32, 1, 3, 22, 102, -22]
print()
print('Bubblesort:')
start = time.time()
ls = b.bubblesort(liste.copy())
slutt = time.time()
print(ls)
print('{0:.3f} seconds'.format((slutt - start)))
print()
print('Selectionsor... |
52ee6e59c2d3477b7a79fc82f50b48d00c46199b | youth-for-you/Natural-Language-Processing-with-Python | /CH-1/Exercises/11.py | 492 | 4.03125 | 4 | #Define several variables containing lists of words,e.g., phrase1, phrase2, and so on.
#Join them together in various combinations (using the plus operator) to form whole sentences.
#What is the relationship between len(phrase1 + phrase2) and len(phrase1) + len(phrase2)?
if __name__ == '__main__':
phrase1 = ['I', ... |
be172b3b278c917d476ef101884bf526e6997862 | youth-for-you/Natural-Language-Processing-with-Python | /CH-1/Exercises/10.py | 680 | 4.125 | 4 | #Define a variable my_sent to be a list of words,using the syntax my_sent = ["My", "sent"]
# (but with your own words, or a favorite saying).
#Use ' '.join(my_sent) to convert this into a string.
#Use split() to split the string back into the list form you had to start with.
if __name__ == '__main__':
my_sent = ['... |
ff5fc8816f876e7265f651cb65c2378b8cf9ae8f | aserbezo/First_step_in_pyton | /# 8 Аквариум.py | 1,022 | 3.90625 | 4 | # Да се напише програма, която изчислява литрите вода, които са необходими за напълването на аквариума
# Един литър вода се равнява на един кубичен дециметър/ 1л=1 дм3/.
# От конзолата се четат 4 ри реда
length = float(input())
width = float(input())
height = float(input())
percent_occupied_by_volume = float(input())
... |
1ea184106441c5fd3c0299400729180f383ee524 | aserbezo/First_step_in_pyton | /# 7 Изготвяне на проекти.py | 168 | 3.796875 | 4 | name = input()
number_project = int(input())
hours = number_project * 3
print(f"The architect {name} will need {hours} hours to complete {number_project} project/s.")
|
f0582f289d989eeb9f6270493798cf56543388eb | HaiyueChen/INF3490 | /week1/1c.py | 604 | 3.90625 | 4 | import numpy as np
import random
import matplotlib.pyplot as plt
def f(x):
return -x**4 + 2*x**3 + 2*x**2-x
def df(x):
return -4*x**3 + 6*x**2 + 4*x - 1
x = np.linspace(-2, 3, 100)
start = random.uniform(-2, 3)
gradient = df(start)
print("gradient start:", gradient)
print("start:", start)
iteration = 0
whi... |
21dedab87f7a15ce3b93d10b7b20df6d4f691a13 | BFriedland/data-structures | /dll/doubly_linked_list.py | 8,067 | 4.3125 | 4 | '''
Contains a DoublyLinkedList class for constructing
doubly-linked lists out of Node objects.
This code borrows heavily from my linked_list.py test suite.
If comparing to linked_list, stack or queue, NOTE that
next and previous have been swapped
because it doesn't make any sense for next to point at
the head when t... |
fda4464a7213636f6e4e30dcdcc3de835c97dd43 | BFriedland/data-structures | /stack/stack.py | 1,562 | 3.921875 | 4 | '''
Contains a Stack class for constructing stacks out of Node objects.
This stack implementation copies heavily from test_linked_list
in my data-structures repository.
Partly adapted from:
http://en.literateprograms.org/Singly_linked_list_%28Python%29
'''
class Stack:
def __init__(self):
self.head = N... |
e1678292d614620a8fa25771d14b4a81ed750891 | BFriedland/data-structures | /radix_sort/test_radix_sort.py | 2,748 | 3.515625 | 4 |
import random
import unittest
import radix_sort as r_s
class test_RadixSort(unittest.TestCase):
def test_randomly(self):
for each_pass in range(0, 1000):
random_order_of_magnitude = (10 ** random.randint(1, 10))
random_list = []
for each_number in range(0, random.ra... |
11ff73edd6eb7d4142a374916bfcf13662ee83ff | poojatathod/Python_Practice | /max_of_list.py | 556 | 4.375 | 4 | #que 13: The function max() from exercise 1) and the function max_of_three() from exercise 2) will only work for two and three numbers, respectively. But suppose we have a much larger number of numbers, or suppose we cannot tell in advance how many they are? Write a function max_in_list() that takes a list of numbers a... |
e3d61428e98c35ba2812b991330964bc362a0f6c | poojatathod/Python_Practice | /translate.py | 1,023 | 4.15625 | 4 | #que 5: Write a function translate() that will translate a text into "rövarspråket" (Swedish for "robber's language"). That is, double every consonant and place an occurrence of "o" in between. For example, translate("this is fun") should return the string "tothohisos isos fofunon".
def translate(string):
c=0
... |
ecc17cab948c55d4262611b10b8cf6152c5297d3 | poojatathod/Python_Practice | /longest_world.py | 401 | 4.34375 | 4 | #que 15: Write a function find_longest_word() that takes a list of words and returns the length of the longest one.
def longest_word(string):
list1=[]
for x in string:
list1.append=len(x)
outpt=max(list1)
outpt1=list1.index(outpt)
outpt2=string[outpt1]
return outpt2
string=input("en... |
d22ec2683b63d8c826feb6c3c501e392e45644b3 | GucciGerm/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/6-print_comb3.py | 173 | 3.859375 | 4 | #!/usr/bin/python3
for n in range(0, 10):
if n != 8:
for j in range(0, 10):
if n < j:
print("{}{}, ".format(n, j), end='')
print(89)
|
27b281e5cfeaf301f1d0d1140c9775cd84f535f5 | GucciGerm/holbertonschool-higher_level_programming | /0x0F-python-object_relational_mapping/model_city.py | 778 | 3.765625 | 4 | #!/usr/bin/python3
"""
This is a python script that creates a class named City
"""
from model_state import Base, State
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
class City(Base):
"""
City - inherits from the base, and links to the MySQL ... |
8e8d9b4f6cca0fba2c9b14d044ae44aa017529d5 | GucciGerm/holbertonschool-higher_level_programming | /0x0A-python-inheritance/1-my_list.py | 589 | 4.28125 | 4 | #!/usr/bin/python3
class MyList(list):
"""
MyList - Created this class to inherit components from list
Args:
list - This is the list that we will be inheriting from
Return:
None, will print the sorted inherited list
"""
def print_sorted(self):
"""
print_sorted - This w... |
04e3213d38a169dee4919acce36d7537edcfd27f | GucciGerm/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/3-say_my_name.py | 590 | 4.46875 | 4 | #!/usr/bin/python3
"""
say my name module
"""
def say_my_name(first_name, last_name=""):
"""
say_my_name -
This function will print "My name is <first><last>"
Args:
first_name - is the users first name
last_name - is the users last name
Return:
None
"""
def say_my_name(first_n... |
5cb752c7cdb291671e11e2955b36b38a1d666db5 | GucciGerm/holbertonschool-higher_level_programming | /0x0A-python-inheritance/9-rectangle.py~ | 981 | 3.90625 | 4 | #!/usr/bin/python3
BaseGeometry = __import__("7-base_geometry").BaseGeometry
"""
Here we are importing the 7-base_geometry function into our rectangle
"""
class Rectangle(BaseGeometry):
"""
Created a rectangle class that inherits from BaseGeometry
"""
def __init__(self, width, height):
"""
... |
162300fb49756e6ba23ac75abbdab98b936346cb | GucciGerm/holbertonschool-higher_level_programming | /0x03-python-data_structures/9-max_integer.py~ | 150 | 3.515625 | 4 | #!/usr/bin/python3
def max_integer(my_list=[]):
holder = ""
for n in my_list:
if n > holder:
holder = n
return holder
|
8b06343d1d12cd050ae44928ebcc321809abb08f | GucciGerm/holbertonschool-higher_level_programming | /0x0B-python-input_output/11-student.py | 772 | 4.21875 | 4 | #!/usr/bin/python3
class Student:
"""
Creating a class named Student
"""
def __init__(self, first_name, last_name, age):
"""
__init__ - Initializing attibutes
Args:
first_name - This is the first name passed
last_name - This is the last name passed
age - ... |
329b1e891665d4fcacf1972f7f6725127d454fbb | aitorlomu/SistemasGestores | /Python/Python/Ejercicios/18.py | 288 | 3.984375 | 4 | numeros=int(input('Introduzca el número de números que se desea introducir '))
suma=0;
cont=1;
num=0;
for i in range (0,numeros):
num=int(input('Introduzca un número'))
suma=suma+num;
media=suma/numeros
print('Se han introducido ',numeros,' números y su media es de ',media)
|
8eee61f3e3f4731bb9fb5ba34ed1501db2ee3c50 | aitorlomu/SistemasGestores | /EjerciciosPython2_AitorLopez/12.py | 669 | 3.578125 | 4 | def deBinAInt(n):
suma=0
for i in range(n-1,-1,-1):
num=int(input(('Introduzca el bit correspondiente a la posición (sólo 0 o 1 o petará el programa) ',i,' ')))
suma=suma+(num*(2**i))
return suma
def deBinAIntdecc(n):
suma=0
for i in range(-1,(n*-1)-1,-1):
num=int(input(('Int... |
bd66de2903f83d8eb6a563ec7f48f894dda9cbf3 | aitorlomu/SistemasGestores | /Python/Python/Ejercicios/07.py | 462 | 3.65625 | 4 | def compruebaVocal(n):
if n=='a' or n=='e' or n=='i' or n=='o' or n=='u' or n=='A' or n=='E' or n=='I' or n=='O' or n=='U':
return True
else:
return False
espacio=False
letra=input('Introduzca una letra ')
suma=0
while letra!=' ':
if compruebaVocal(letra):
print('Es vocal')
... |
430e846512c2940d3e23e54021c1ee2b0a58ee90 | aitorlomu/SistemasGestores | /Python/Python/Ejercicios/03.py | 110 | 3.71875 | 4 | n=int(input('Introduzca un número '))
i=1
suma=0
while(i<=n):
suma+=(n**2)/(i)
i=i+1
print (suma)
|
7e1862d84df0221503be876775e5f752e6a994a4 | aitorlomu/SistemasGestores | /Python/Python/Ejercicios/09.py | 236 | 4.15625 | 4 | num=int(input('Introduzca el número de números que introducirá '))
max=0
for i in range(0,num):
introducido=int(input('Introduce un número '))
if introducido>max:
max=introducido
print('El máximo valor es ',max)
|
3c403aebce458271cc65041f15a420abb8f010b3 | Cipher-007/Python-Program | /Convert_miles_to_Km.py | 237 | 4.375 | 4 | #Converting Miles to Kilometers
miles = float(input("Enter Miles to be converted into Kilometers: "))
#Conversion factor
conversion_factor = 1.609
#Conversion
kilometers = miles * conversion_factor
print(f"{miles}mi is {kilometers}Km") |
2bcb9ae2103a72c5a215c2e3e3a564d5fa53259d | Cipher-007/Python-Program | /Area_of_Triangle.py | 382 | 4 | 4 | #Area of Triangle
first_side = float(input("Enter measurement of first side: "))
second_side = float(input("Enter measurement of second side: "))
third_side = float(input("Enter measurement of third side: "))
#semiparameter
s = (first_side + second_side + third_side) / 2
#area
area = (s*(s-first_side)*(s-second_side)... |
2a63a6e4bb336c88af0c8fe549fd868a563fc2d9 | mattwynn1/scrapingire15 | /simple.py | 1,342 | 4.09375 | 4 | #We need some basic libraries to get started.
import requests # "An elegant and simple HTTP library for Python." Gets us around the web.
from bs4 import * # "A library for pulling data out of HTML and XML files."
import csv # "implements classes to read and write tabular data in CSV format"
# First, we identify the p... |
5e4bb90b6e977c5ca29ad6f4784dbc80723ccae1 | kyroschow/kens-stuffs | /longest-word.py | 233 | 3.859375 | 4 | sentence = input("Text: ")
maxWordSize = 0
lastNotAlpha = -1
for i in range(len(sentence)):
if not sentence[i].isalpha():
maxWordSize = max(maxWordSize, i - lastNotAlpha - 1)
lastNotAlpha = i
print(maxWordSize)
|
92575c83aa34a2e3d7b06b3fdf55547a9c7ea8ae | sachinsaxena021988/Assignment3 | /findmaxLength.py | 262 | 3.640625 | 4 | #import functools to use reduce
from functools import reduce
#define listword
list_words = ["getallY","ysduadhks","dfafafa","affasfwrwetgerhruul","morutujtjtutuning"]
#reduce all with length
reduce((lambda x,y:y if len(y) > len(x) else x), list_words ) |
aba2774a9578d3086edeb7d534fbc3ac31a02a66 | seeinger/OpenCollegePythonWebProject | /session0_20191130/session0-1.py | 287 | 3.765625 | 4 | # a라는 박스에 2를 넣는다/
# = 은 같다라는 뜻이 아니다. 저장한다는 뜻이다!!
from typing import Type
a = 2
b = 3.14
c = "안녕하세요"
print(a)
print(b)
print(c)
type_a = type(a)
type_b = type(b)
type_c = type(c)
print(type_a)
print(type_b)
print(type_c)
|
f51e7b37358ddcd9ec10a1bd373167f1b9292666 | seeinger/OpenCollegePythonWebProject | /session3_20200111/session3-practice2.py | 507 | 3.90625 | 4 | def calcMax(number_list):
return max(number_list)
def calcMin(number_list):
return min(number_list)
def calcAvg(number_list):
sum = 0
for a in numbers:
sum = sum + a
return sum / len(numbers)
numbers = input("숫자들을 입력하세요: ")
max_result = calcMax(numbers.split())
min_result = calcMin(number... |
21a188ebac52a9a4d7be613c918fae9c37803c21 | dspohnholtz/cs4410 | /spohnholtz_homework1.py | 692 | 3.8125 | 4 | #Troy University, CS4410
#Created By: Daniel Spohnholtz
#Homework 1
import pandas as pd
import matplotlib.pyplot as plt
#Import dimonds.csv from github
url = 'https://raw.githubusercontent.com/dspohnholtz/cs4410/main/diamonds.csv'
df = pd.read_csv(url, index_col=0)
#Display First Seven Rows
print("FIRST ... |
3157139c894d6aad71039e0e76381d236aac4281 | Interligo/py101-tasks | /word_freq.py | 2,252 | 3.8125 | 4 | """
Программа считает Топ-100 слов для переданного ей текстого файла.
Путь до текстового файла передается программе в виде аргумента
В выводе не должно быть стоп-слов (междометий, союзов, местоимений и т.д.)
Список стоп-слов можно взять из популярного пакета nltk
Тебе может понадобится модуль os, модуль argparse, цик... |
49d014a1cac591686a0249a56777929419a4ec1c | y-oksaku/Competitive-Programming | /AtCoder/abc/131a.py | 117 | 3.671875 | 4 | S = input()
for s in range(3) :
if S[s] == S[s+1] :
print('Bad')
break
else :
print('Good')
|
777ec4374e8df2f4ff7c9f0750952c213fcd4f72 | y-oksaku/Competitive-Programming | /AtCoder/abc/140e_3.py | 2,312 | 3.515625 | 4 | class UnionFind :
def __init__(self, size) :
self.parent = list(range(size))
self.height = [0] * size
self.size = [1] * size
self.component = size
def root(self, index) :
if self.parent[index] == index : # 根の場合
return index
rootIndex = self.root(self... |
78b94070ed93ae1f0ba7525fe013020bc6284db3 | y-oksaku/Competitive-Programming | /AtCoder/arc/003a.py | 219 | 3.578125 | 4 | N = int(input())
R = input()
score = 0
for r in R:
if r == 'A':
score += 4
elif r == 'B':
score += 3
elif r == 'C':
score += 2
elif r == 'D':
score += 1
print(score / N) |
950a8eccebe55eed65acbc7acbde7f284a741032 | y-oksaku/Competitive-Programming | /AtCoder/abc/148a.py | 96 | 3.5 | 4 | A = int(input())
B = int(input())
for i in range(1, 4):
if not i in [A, B]:
print(i) |
24947e8d318a47a672dfc5f967e3bbfb4743952e | y-oksaku/Competitive-Programming | /AtCoder/abc/128b.py | 335 | 3.6875 | 4 | N = int(input())
A = []
# 出力を受け取る
for i in range(N):
Si , Pi = input().split()
Pi = int(Pi) # 型変換
A.append([i,Si,Pi])
# リストにアクセス
second = lambda A : A[1]
third = lambda A : A[2]
# ソート
A.sort(key=third,reverse=True)
A.sort(key=second)
for target in A:
print(target[0] + 1) |
20909bc2cd33af954b7ef41ce165a10ecafe3483 | y-oksaku/Competitive-Programming | /AtCoder/abc/071b.py | 180 | 3.953125 | 4 | from string import ascii_lowercase
S = input()
D = dict()
for s in S:
D[s] = True
for s in ascii_lowercase:
if not s in D:
print(s)
exit()
print('None')
|
ef46c5c8f2a24629c9018b30a807244ebfc062aa | y-oksaku/Competitive-Programming | /AtCoder/abc/155b.py | 180 | 3.546875 | 4 | N = int(input())
A = list(map(int, input().split()))
A = [a for a in A if a % 2 == 0]
if all(a % 3 == 0 or a % 5 == 0 for a in A):
print('APPROVED')
else:
print('DENIED')
|
d7479421d65761720b5628a102df82ded1b51fbe | y-oksaku/Competitive-Programming | /AtCoder/agc/021a.py | 205 | 3.53125 | 4 | N = int(input())
if N < 10:
print(N)
exit()
def digitSum(n):
return sum([int(a) for a in str(n)])
ans = max(digitSum(10**(len(str(N)) - 1) - 1) + int(str(N)[0]) - 1, digitSum(N))
print(ans) |
c2618deb018a2a76dfd9fe02c19b07cd40ed78fc | y-oksaku/Competitive-Programming | /AtCoder/abc/048d.py | 141 | 3.75 | 4 | S = input()
if S[0] == S[-1]:
print('First' if len(S) % 2 == 0 else 'Second')
else:
print('First' if len(S) % 2 == 1 else 'Second')
|
6b56a6b180618652b3482545076f135150d49010 | y-oksaku/Competitive-Programming | /AtCoder/abc/018a.py | 134 | 3.65625 | 4 | A = [int(input()) for _ in range(3)]
B = {a : i for i, a in enumerate(sorted(A, reverse=True), start=1)}
for a in A:
print(B[a])
|
d6b16f005f6209fc1b8bc1ef5d7c5ff82e379de4 | y-oksaku/Competitive-Programming | /AtCoder/abc/017b.py | 105 | 3.625 | 4 | S = input()
for s in ['ch', 'o', 'k', 'u']:
S = S.replace(s, '')
print('YES' if S == '' else 'NO')
|
1b8d8352e349e589f6526aa6c92c5a322ade55de | y-oksaku/Competitive-Programming | /AtCoder/arc/026b.py | 437 | 3.71875 | 4 | # 約数の全列挙
def divisors(n):
divisors = []
for i in range(1, int(n**0.5)+1):
if n % i == 0:
divisors.append(i)
if i != n // i:
divisors.append(n//i)
return divisors
N = int(input())
div = divisors(N)
sumDiv = 0
for d in div:
if d != N:
sumDiv += d
... |
50d16d5b6d21e51603944afa69711b5b07b04794 | y-oksaku/Competitive-Programming | /AtCoder/abc/146a.py | 134 | 3.640625 | 4 | S = input()
week = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT']
for i, w in enumerate(week):
if S == w:
print(7 - i) |
b72e1006e93f9d9469194efeaa1cdea3369eccf3 | y-oksaku/Competitive-Programming | /AtCoder/agc/003a_2.py | 200 | 3.578125 | 4 | from collections import Counter
S = Counter(input())
def isNotOk():
WE = (S['W'] > 0) ^ (S['E'] > 0)
NS = (S['N'] > 0) ^ (S['S'] > 0)
return WE or NS
print('No' if isNotOk() else 'Yes')
|
cbcc8d1790e13c434ed06f9155d729bfd1ed6776 | ranie2019/PythonBasico | /exercicos 7.py | 352 | 3.65625 | 4 | def maior(colecao):
maior_item = colecao[0]
for item in colecao:
if item > maior_item:
maior_item = item
return maior_item
def menor(colecao):
menor_item = colecao[0]
for item in colecao:
if item < menor_item:
menor_item = item
return menor_item
print(me... |
365043d53d1d41a3ca566d37115a84609e490dfe | robnit/illegal_hacking_tools.exe | /monthlypayment.py | 1,032 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 26 12:13:40 2017
@author: Linux
"""
balance = 999999
annualInterestRate = 0.18
lowerbound = balance/12
upperbound = balance*(1+annualInterestRate)/12
monthlyPaymentRate = round((upperbound+lowerbound)/2,2)
Rate = 0
# Remaining balance: 31.38
def yearly(balance,annualIn... |
2e44cfff6461f02fcf1b88685d7a5f93fb4e10ce | henryln1/CS224U-Project | /data_processing.py | 8,238 | 3.6875 | 4 | import math
import random
from collections import defaultdict
import os
cornell_movie_delimiter = ' +++$+++ '
#directory_location = '../cornell-movie-dialogs-corpus/'
title_metadata_txt_file = 'movie_titles_metadata.txt'
characters_metadata_txt_file = 'movie_characters_metadata.txt'
conversations_txt_file = 'mo... |
8c9092b75b18bbde2a0bd9f0a59243cb1ec4ade8 | nptravis/python-studies | /crack.py | 890 | 3.875 | 4 | import crypt
import sys
def main():
while
# Get hash from user
try:
p = sys.argv[1]
except Exception:
print("Error, Usage: program.py <hash>")
exit(1)
salt = p[0] + p[1]
password = ['A']
string_pass = ''.join(password)
# crack the hash
def loop(password):
while True:
# check all lower ca... |
0cd2e529b3c9904df186c045149954f46e0200a3 | nptravis/python-studies | /vigenere.py | 1,099 | 4.0625 | 4 | import sys
def main():
# variables
try:
key = sys.argv[1]
except IndexError:
print("Error! Usage: program.py <key>")
exit(1)
plaintext = ""
while plaintext == "":
plaintext = input("Input plaintext: ")
if plaintext == "":
print("Must add some plaintext!")
key = key.lower()
key_array = []
key_in... |
6aa80791b717816f5c9969add0371885a6f87078 | Page007/Data-Structure-And-Algorithms | /itw2.py | 1,443 | 3.984375 | 4 | '''
This is a rudimentary code for flagged Fibonacci generator which is one of the most commonly used PRNG method.
We assume that the operator in the FFG method is bitwise EXOR of the numbers.
'''
import random
import math
print('Enter any 4 numbers of your choice')
b = list()
for i in range(4):
b.append(i... |
f850858987f3402587f3349cc377ec4bf6501826 | m8k7j/advanced_python | /advanced_func/func_object.py | 1,217 | 3.96875 | 4 | def foo(text):
return len(text)
def show(func):
size = func("zen of python")
print("length of string is: %s" %size)
def nick():
return foo
def get_length(text): # get_length()-->new_text = clean(text) --> clean(t)
def clean(t):
return t[1:]
new_text = clean(text... |
045343d7edbf14458bd905a01502d10d75c493ce | m8k7j/advanced_python | /asyncio_investigate/yieldfrom.py | 1,641 | 3.953125 | 4 | #coding:utf-8
"""
different from yield and yield from
"""
def iterator(n):
item = 0
while item < n:
r = yield item
if r is None:
item += 1
else:
item += r
def generator(n):
yield from iterator(n)
def accmulate():
tally = 0
... |
cabb8cd84da1dcaa15b739d2165efb24eea628f6 | shi22a/phython_225 | /14.py | 169 | 3.78125 | 4 | import math
AB=int(input("length AB= "))
BC=int(input("length BC= "))
AC=(AB**2+BC**2)**(1/2)
ab=math.asin(AB*math.sin((90* math.pi / 180))/AC)
print(ab*180/math.pi )
|
0c6b939bc56383456402855cd6a6ab70cddd27d9 | sauravkr41999/pythonproject | /assignment2/fabonicci series of 3variable.py | 81 | 3.5 | 4 | a=0
b=1
c=2
for i in range(10):
d=a+b+c
a=b
b=c
c=d
print(d)
|
4b8c9d6c401c6b590f4f73965b2c3315642fb8a5 | JeremyBrightbill/Advent-of-Code | /2020/day_10.py | 2,616 | 3.90625 | 4 | """--- Day 10: Adapter Array ---
https://adventofcode.com/2020/day/10"""
DAY: int = 10
from utilities import load_data
from functools import reduce
import operator
# Import -------------------------------------
# Puzzle input
data_raw = [int(item) for item in load_data(2020, DAY)]
data = [0] + sorted(data_raw) + [... |
b3a22b7a3e4614ff72f6b2c278aea75366fcdb98 | JeremyBrightbill/Advent-of-Code | /2020/day_02.py | 1,575 | 3.953125 | 4 | """--- Day 2: Password Philosophy ---
https://adventofcode.com/2020/day/2"""
DAY: int = 2
from collections import namedtuple
from utilities import *
# Import -------------------------------------
# Sample data
sample1 = '13-15 b: bbbbbbbbbbbbgbb'
# Puzzle input
data: list = load_data(2020, DAY)
# Solve part 1 -... |
73579fb6f711ef5d9264fe76a899f27c365a9bec | BuiTran/05tbui13 | /MatplotCharting.py | 1,370 | 3.75 | 4 | '''
Created on Nov 23, 2015
@author: TranBui
'''
import matplotlib.pyplot as plt
from ViewPort import ViewPort
class MatplotCharting(object):
'''
Plotting the graph from the data using matplotlib
'''
def __init__(self, stockReader):
'''
Constructor
'''
x = [s.date for... |
b5e2b660b040820904115203765e6106915b2768 | mohitmv/taskon | /taskon/tests/sample_tasks.py | 1,087 | 3.71875 | 4 | import time
def makeSandwitch(bread, onion, grill_duration):
print("Cutting " + onion)
print("Grilling " + bread + " for " + str(grill_duration)+ " minutes")
return onion + "-Sandwitch"
def makeBread(flour):
print("Processing " + flour)
return "Bread"
def buyOnion():
return "Onion"
def makeF... |
96db080582e7eccb870d96d2b8deb4e5a09e097e | pawdon/python_course | /week06_day02/w06d02.py | 5,101 | 3.671875 | 4 | import random
def test01():
my_list = [1, 2, 3]
my_number = 3
func1 = lambda a_number: [i * a_number for i in my_list]
func2 = lambda a_list: [my_number * i for i in a_list]
print(func1(4))
print(func2([3, 4]))
return func1, func2
def test02():
my_list = [11, 12, 13]
my_number... |
05eebf5900f66e543ed755bf7248110576a5cc64 | pawdon/python_course | /week03_day01/object_programming.py | 11,443 | 4 | 4 | class MyClass:
def __init__(self):
print('haha')
self.x = 0
class Point2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
# wywolywane niejawnie podczas str(p1), a funkcja str jest wywolywana niejawnie w print
return f'P({self.x}, {self.... |
c8540801851b4a34b60d07c4be82335119764fcf | pawdon/python_course | /week03_day02/functional_programming.py | 2,613 | 3.640625 | 4 | def double_x(x):
return 2 * x
def triple_x(x):
return 3 * x
def modify_x(x, func):
result = func(x)
return result
def quadratic_equation(a, b, c):
def delta(a, b, c):
return b ** 2 - 4 * a * c
x1 = (-b + delta(a, b, c) ** 0.5) / 2
x2 = (-b - delta(a, b, c) ** 0.5) / 2
ret... |
352231acb77b2f54c15df747ec2d98514bbb3427 | toby20-meet/meet2018y1lab5 | /fruit_sorter.py | 224 | 4.15625 | 4 | new_fruit = input("What fruit would you like to choose?")
if "Apple"== new_fruit:
print('Bin1')
elif "Orange" == new_fruit:
print('Bin2')
elif 'Pear' == new_fruit:
print('bin3')
else:
print("wtf dis froot?")
|
58fa7dd2ac1c58db54d06a809b5f3ae0c31b9c38 | Srinjoy-Santra/Data-science-projects | /Currency Exchange Rates/plot_exchange.py | 381 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 19 12:03:54 2019
@author: nEW u
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Opening the dataset
df=pd.read_csv(r'C:\Users\nEW u\Desktop\cse\Python\Data Science\3 months DS\Data-science-projects\Currency Exchange Rates\exchange_rate.csv')... |
dbee062b6158419ff1b19278a10bde7140316670 | zhwhong/OJ | /algorithm-and-data-structure/test/test_sort.py | 898 | 3.546875 | 4 | import sort
import random
def get_random_arr(n):
return [random.randint(0, 100) for _ in range(n)]
def test_merge_sort():
for _ in range(500):
r = random.randint(0, 100)
arr = get_random_arr(r)
assert sort.mergesort(arr) == sorted(arr)
def test_quicksort():
for _ in range(500):... |
119cb67f7fd5f0b6c74fced04f5c7746d60a09cb | helinkoo/2019HuaweiSC | /Cross.py | 4,569 | 3.578125 | 4 | from Road import RoadS
from Car import Cars
class Cross(object):
def __init__(self, crossInfo):
self.crossId = crossInfo[0]
self.roadIds = [crossInfo[1], crossInfo[2], crossInfo[3], crossInfo[4]]
self.x = 0
self.y = 0
self.done = False
self.validRoadIndex = []
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.