blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
b808a6bf6c4720eaa1d1e4269a704787cfc0dc23 | DikranHachikyan/CPYT210713 | /ex72.py | 1,092 | 4.03125 | 4 | from draw.point import Point
class Rectangle(Point):
def __init__(self, x = 0, y = 0, width = 0, height = 0, *args, **kwargs):
super().__init__(x,y) # констр. на родител
print('Rectangle Ctor')
self.width = width
self.height = height
@property
def width(self):
re... |
20c2897beadbac4fe65957edaf6ce66c22cf0224 | wk0/pypipie | /backend.py | 1,463 | 3.59375 | 4 | """
generate_pi code based off Classic Computer Science Problems in Python's Section 1.4
* https://github.com/davecom/ClassicComputerScienceProblemsInPython/blob/master/Chapter1/calculating_pi.py
async generator docs:
* https://www.python.org/dev/peps/pep-0525/
* Check out the example near the end of the page
async ... |
067505e21b87c82061e842f0b3b2be2a8d1214b2 | nikhiljsk/Programming | /Python/quick_sort.py | 666 | 4.0625 | 4 | #quick sort 1st iteration
def quickSort(arr):
pivot = arr[0]
loop1 = 1
loop2 = len(arr)-1
right = len(arr) -1
left = 1
while right > left-1:
for left in range(loop1, loop2):
if arr[left] > pivot:
break
for right in range(loop2,loop1,-1):
... |
a5149b51bd71842f879af5fe43781bdb5dcc4998 | grungydan/next_prime | /next_prime.py | 1,075 | 4.34375 | 4 | '''
A simple program that asks the user if they would like to see the next positive prime number,
and if so, generates and provides that number.
'''
# initial program output
print("The first positive prime number is 2.\n")
# function to determine prime
def is_prime(num):
if num % 2 == 0:
return False
... |
dbad0a8bc22612596655057541415bef62feee5b | axelFrias1998/CrashCourseOnPythonExercises | /Fourth week/Dictionaries/Iterating over the Contents of a dictionary/iteratingOverDictionaries.py | 654 | 4.125 | 4 | file_counts = {"jpg": 10, "txt":14, "csv":2, "py":23 }
for extension in file_counts:
print(extension)
for extension, amount in file_counts.items():
print("There are {} files with the .{} extension".format(amount, extension))
hola = "Hola"
hola.replace()
hola.isle
print(file_counts.keys())
print(file_counts.va... |
b3f17b18bb1a64aa714a97d133f22d87fd85abd0 | MaelsVilen/repo_github | /Basics/lesson_4/ex7.py | 696 | 3.625 | 4 | """Реализовать генератор с помощью функции с ключевым словом yield, создающим очередное значение.
При вызове функции должен создаваться объект-генератор.
Функция должна вызываться следующим образом: for el in fibo_gen().
Функция отвечает за получение факториала числа, а в цикле необходимо выводить только первые 15 ч... |
5390a39f44b432ab7beaff4069a8a225c70d58ad | phibzy/InterviewQPractice | /Solutions/ValidateStackSequences/valStack.py | 3,445 | 3.859375 | 4 | #!/usr/bin/python3
"""
@author : Chris Phibbs
@created : Monday Mar 01, 2021 11:01:52 AEDT
@file : valStack
"""
"""
Questions:
- Pushed array: Does element order correspond to order they were pushed?
- Can a value have been pushed more than once?
- Same for pop list
- Can either... |
cecdc791f739ec874b9732d80aebc5bcad65f446 | anonymous-c0de/esop-2022 | /numeric_optics/initialize.py | 618 | 3.59375 | 4 | """ Initializers are (random) choices of initial parameters """
import numpy as np
def normal(mean=0, stddev=0.01):
def normal_initializer(shape):
return np.random.normal(mean, stddev, shape)
return normal_initializer
# eq (16) http://proceedings.mlr.press/v9/glorot10a/glorot10a.pdf
def glorot_uniform... |
c824762c07045ea002f788e8afba029c782f11d7 | Viheershah12/python- | /Practice_Projects/compare_lists.py | 196 | 3.5625 | 4 | a=[12,3,5,8,90,11,44,66,8,9,34,56]
b=[12,3,3,3,3,3,3,3,3,3,3,3,3,3,10]
c=[]
for item in a:
if item in b:
if item not in c:
c.append(item)
for i in c:
print(i,end="\t") |
ce461ca6acdbdf1d6712d7507e463fd7ad9e44e0 | PVyukov/GB_HW | /Lesson1_welcome/1_all.py | 2,119 | 3.84375 | 4 | # Task 1
a = 'hello'
b = 'world'
print(a, b)
num_1 = int(input())
print('Вы ввели: ', num_1)
# Task 2
time = int(input('Enter time in seconds: '))
hours = time // 3600
minutes = (time // 60) - (hours * 60)
seconds = time % 60
print(f'{hours:02}:{minutes:02}:{seconds:02}')
# Task 3
n = input('Enter integer: ')
print(f... |
695b482ff05d1afc2b215493714849a6ea78c209 | rt17kobi/Personal-Programming-Project | /Simplex.py | 6,280 | 3.578125 | 4 | ###### imports ######
import numpy as np
import matplotlib.pyplot as plt # used for plotting the curves
###### simplex-algorithm ######
def simplex(x0, objfun, alpha=1, beta=0.5, gamma=2, delta=0.5, btol=24.899208, maxiter=10000):
'''
x0: starting point
objfun: objective f... |
4f17eea175b31761417e48689a7b5373b08632f0 | Lonabean98/pands-problems | /squareroot.py | 1,917 | 4.3125 | 4 | # Keith Brazill (G00387845)
# 16th March 2020
# Write a program that takes a positive floating-point number as input and
# outputs an approximation of its square root.
# You should create a function called sqrt that does this.
#Example: Please enter a positive number: 14.5
# The square root of 14.5 is a... |
1d61788e1c9bc48c3a1d130d1010c627690257f0 | NortheastState/CITC1301 | /chapter5/ch5Example4.py | 2,377 | 4.3125 | 4 | # ===============================================================
#
# Name: David Blair
# Date: 03/10/2018
# Course: CITC 1301
# Section: A70
# Description: Looking at the split function
# and other string functions
#
# ===============================================================
... |
51dc2db0f5efea9eb099a17e0fd1c63ebfaf8904 | Northwestern-CS348/assignment-3-part-2-uninformed-solvers-avarobinson | /student_code_uninformed_solvers.py | 6,726 | 3.59375 | 4 | from solver import *
from collections import deque
class SolverDFS(UninformedSolver):
def __init__(self, gameMaster, victoryCondition):
super().__init__(gameMaster, victoryCondition)
def solveOneStep(self):
"""
Go to the next state that has not been explored. If a
game state le... |
709c7ce699879e937fda38ca21049a544492f66e | vScourge/Advent_of_Code | /2018/07/2018_Day_07a.py | 1,344 | 3.75 | 4 | """
Step X must be finished before step Z can begin.
"""
import string
### CLASSES ###
class Step( ):
def __init__( self, id ):
self.id = id
self.reqs = [ ] # Other steps that are prerequisites
def __repr__( self ):
return '<Step {0}>'.format( self.id )
### FUNCTIONS ###
def parse_input( ):
steps... |
c2b676c1702efd4fdce0361ee19146bc933377a2 | SANDHIYA11/myproject | /B23.py | 188 | 4.0625 | 4 | from array import *
x=array('i',[])
a=int(input("Enter the number:"))
for i in range(a):
n=int(input("Enter the numbers:"))
x.append(n)
print("The minimum number is:", min(x))
|
978cd50043cc54e789069cb2523c312b6ba526f1 | frankobe/lintcode | /154_regular-expression-matching/regular-expression-matching.py | 2,648 | 3.640625 | 4 | # coding:utf-8
'''
@Copyright:LintCode
@Author: frankobe
@Problem: http://www.lintcode.com/problem/regular-expression-matching
@Language: Python
@Datetime: 16-09-28 01:21
'''
class Solution:
"""
@param s: A string
@param p: A string includes "." and "*"
@return: A boolean
"""
de... |
1636d8a10e994ebb2b14ecf51a84e53aacf9623f | garthus23/holbertonschool-higher_level_programming | /0x06-python-classes/1-square.py | 226 | 4.03125 | 4 | #!/usr/bin/python3
"""
class of square
"""
class Square:
"""
Class that defines a square
Attributes:
size (size): this is the size
"""
def __init__(self, size):
self.__size = size
|
90dc1a1fc120f3ac524c17cb8df06051b0e8fd13 | MarquisVIP/data-structures-and-algorithms-in-python | /Reference/progs/list_linked1.py | 1,789 | 3.859375 | 4 | """ 带尾结点引用的单链表类 """
from list_node import LNode, LinkedListUnderflow
from list_linked import LList
class LList1(LList):
def __init__(self):
LList.__init__(self)
self._rear = None
# def prepend(self, elem):
# self._head = LNode(elem, self._head)
# if self._rear is... |
de43dc5aea0849fb4d97acb8a314cb60e91bb7bc | gjwei/leetcode-python | /easy/Reverse Integer.py | 496 | 3.671875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
created by gjwei on 4/24/17
"""
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
result = 0
while x:
tail = x % 10
new_result = result * 10 + tail
... |
11ee86ba2cabaebb329b9138f44a483b60e75b6b | c4rl0sFr3it4s/Python_Basico_Avancado | /script_python/calculo_distancia_viagem__031.py | 415 | 3.828125 | 4 | '''entre no programa a distância de uma viagem em KM saia com o preço da
passagem cobrando R$0.50 por KM para viagens de até 200KM e R$0.45 para viagens mais longas'''
distancia = float(input('Qual a distância da viagem em (KM): '))
preco = distancia * 0.5 if distancia <= 200 else distancia * 0.45
print(f'Para \033[1... |
2a561c87b52cb074dfb47abb45f75f0025b743f6 | MichelfrancisBustillos/PythonPrograms | /DartBoard/DartBoard_Round.py | 1,345 | 3.609375 | 4 | __author__ = 'Michelfrancis Bustillos'
import random
def main():
global greenRadius
global purpleRadius
global redRadius
greenRadius = 1
purpleRadius = 2
redRadius = 3
greenHits = 0
purpleHits = 0
redHits = 0
missHits = 0
throws = eval(input("How many darts would you like to throw? "))
global fout
wit... |
93f4ca110db7cb0ddaac867963d063291645adae | Benj0t/BC_Python | /day00/ex03/count.py | 659 | 3.78125 | 4 | import sys
i = 0
for arg in sys.argv:
i = i + 1
if (i != 2):
print("ERROR")
sys.exit()
def text_analyzer(str):
low = 0
upp = 0
car = 0
ponct = 0
spac = 0
for char in str:
car += 1
if (char == char.upper() and char.isalpha() == True):
upp += 1
elif (char == char.lower() and char.isalpha() == True):
... |
9cda393c69f2f18542a6277022005abd61d18ee9 | IuriiPivtorak/EPAM-homeworks | /homework-6/Prop descriptor.py | 1,879 | 3.8125 | 4 | #!/usr/bin/env python3.6
# Декоратор - это обертка для функции, которая позволяет
# трансформировать внутреннюю функцию, как мы хотим.
# Дескриптор делает похожее, переписывая протоколы __get__,
# __set__ и __delete__, поэтому сделав атрибут класса экземпляром
# декскриптора, мы можем воздейстовать на этот атрибут.
c... |
eed9e7b42076c3f02b6250c2aa405785edc63dcd | christinajensen/hackbright-intro | /conditionals.py | 639 | 4.34375 | 4 | my_name = "Christina"
your_name = "Laura"
if (my_name < your_name):
print "My name is greater!"
elif (my_name > your_name):
print "Their name is greater!"
else:
print "Our names are equal!"
date = 4
halfway = 15
if (date >= halfway):
print "We're halfway there"
else:
print "the month is still you... |
fb62e5e20f409e10b41c224d6754da306a03377b | maiduydung/Algorithm | /unique_num_of_occurence.py | 374 | 3.59375 | 4 | # https://leetcode.com/problems/unique-number-of-occurrences/
class Solution:
def uniqueOccurrences(self, arr: List[int]) -> bool:
hashset = set()
count = 0
count_arr = []
for i in arr:
hashset.add(i)
for j in arr:
if j in hashset:
... |
8f2479fd1443ab65e273fd0f96c2798f5460e12e | bitcsdby/Codes-for-leetcode | /java/Valid Parentheses.py | 1,309 | 3.75 | 4 | class Solution:
# @return a boolean
def isValid(self, s):
count = 0;
small = 0;
mid = 0;
big = 0;
tmp = [];
while count < len(s):
if s[count] == '(':
#small = small + 1;
tmp.append(1);
elif s[count] ... |
ff982db343048162dfc2583462f395b964e347ec | suifenggyy/MachineLearning | /MachineLearning/Matplotalib/Matplotlib/pyplot/001-plot.py | 325 | 3.578125 | 4 | import matplotlib.pyplot as plt
import numpy as np
t = np.arange(-1, 2, .002)
s = np.sin(2 * np.pi * t)
m = t
plt.plot(t, s)
plt.plot(t, m)
# draw a thick red hline at y=0 that spans the xrange
plt.axhline(y=0, linewidth=2, color='r')
plt.axvline(x=0, ymin=0.5, linewidth=2, color='b')
plt.axis([-1, 2, -1, 2])
plt.sh... |
a2684df704829f3accd7742cf9a290d291c37519 | arman81/sentiment-analysis | /vectorizer.py | 1,493 | 3.546875 | 4 |
import nltk
from nltk.tokenize import word_tokenize
from nltk.tokenize import sent_tokenize
from nltk.stem import WordNetLemmatizer
from nltk.stem import PorterStemmer
# Tokenization
def tokenize(text):
tokens = word_tokenize(text)
return tokens
def tokenizeSentence(para):
sentences = sent_tokenize(para)... |
47018452a40336dfa9613fdbef55a0c68b578ab8 | weilaidb/PythonExample2 | /Gui/t12.py | 219 | 3.71875 | 4 | from tkinter import *
root = Tk()
lb = Listbox(root)
for i in range(10):
lb.insert(END,str(i))
lb.delete(1,3) #1-3被删除。lb.delete(0,END)会删掉所有item
lb.pack()
root.mainloop() |
6926c15d9f5381096a47ab846532830c70223a1a | kennethpu/HackerRank | /Algorithms/Warmup/Halloween Party/halloween-party.py | 179 | 3.609375 | 4 | T = int(raw_input())
# Find the maximum product a*b where a+b = K. This is maximized when a=K/2
for i in xrange(T):
K = int(raw_input())
a = K/2
b = K-a
print a*b |
e3e6683cef03bc97fc098c9229f7ed4b8b71668f | hith3107/area-of-circle-python | /area of circle.py | 176 | 4.28125 | 4 |
r=float(input("input the radius of circle:",))
import math
A=math.pi*r**2;
print("The area of circle with radius", end = '')
print(float(r),end = ' ')
print("is:",A)
|
7a6b5c2cab18fee47bfa28effc80dc2ad2ae5a1a | danielchen79/fluent-python | /Ch1 Python Data Model/cards.py | 1,249 | 3.8125 | 4 | import collections
from random import choice
Card = collections.namedtuple("Card", ["rank", "suit"], verbose=False)
class PokerDeck():
ranks = [str(n) for n in range(2,11)] + list('JQKA')
suits = "spades diamonds clubs hearts".split()
def __init__(self):
self._cards = [Card(rank, suit) for suit i... |
7a7f79990671fb57e00492df9a7686411bd642fe | trenator/PfCB | /chapter_4/list_length.py | 189 | 3.78125 | 4 | characters = ["Pip", "Joe", "Estella"]
print("There are " + str(len(characters)) + " characters")
characters.append("Miss Havisham")
print("Now there are " + str(len(characters)) + " characters")
|
52bc357eddac6ae6342bf7f875f2833120bde657 | shubha-rajan/advent-of-code | /day6/part-one/main.py | 653 | 3.578125 | 4 | from collections import defaultdict
def readdata():
data = []
with open("../input.txt") as f:
for line in f:
data.append(line)
return data
def count_orbits(orbits):
graph = defaultdict(lambda : None)
orbit_count = 0
for orbit in orbits:
objects = orbit.split(")")
... |
c6f98a3da116ae76aa61a4b9ee46d8bbde5b98de | fnnntc/leetcode | /search/976. Largest Perimeter Triangle. Largest Perimeter Triangle.py | 706 | 4.03125 | 4 | """Given an array A of positive lengths, return the largest perimeter of a triangle with non-zero area, formed from 3 of these lengths.
If it is impossible to form any triangle of non-zero area, return 0.
Example 1:
Input: [2,1,2]
Output: 5
Example 2:
Input: [1,2,1]
Output: 0
Example 3:
Input: [3,2,3,4]
Output:... |
e570bd18df797bfe378feee640edb7c6c6d5e349 | andriinovak/learn_python | /python_decorators_iterators/test_module.py | 1,103 | 3.640625 | 4 | import unittest
from unittest.mock import Mock, call
import module
from module import main_routine
class test_module(unittest.TestCase):
def test_main_routine_calls_Manager_methods(self):
"""Test methods calls one by one."""
module.Manager.a = Mock()
module.Manager.b = Mock()
mo... |
b0cc96b834fe6ce7cd227d5124961b45d0d086b9 | daxiongpro/Deal_with_Excel | /test/dicTest2.py | 531 | 3.765625 | 4 | # Time: 2020/4/26-11:27
# Author: Rex
import collections
ls = ['a', 'b', 'c', 'a']
# dic = {
# 'a': 1,
# 'b': 2,
# 'c': 3,
# 'a': 4
# }
def list_to_dict(lst):
'''
:param list: 重复元素的列表。ls = ['a', 'b', 'c', 'a']
:return: {'a': [0, 3], 'b': [1], 'c': [2]}
'''
dic = {}
for value... |
29c4e04ca4f9894f1d6bb1cc95d07492676e3982 | JVvix/tkinikerTutorial | /radio_buttons.py | 723 | 4 | 4 | from tkinter import *
root = Tk()
root.title("Radio Buttons")
TOPPINGS = [
("Pepperoni", "Pepperoni"),
("Cheese", "Cheese"),
("Mushroom", "Mushroom"),
("Onion", "Onion")
]
pizza = StringVar()
pizza.set("Pepperoni")
for text, topping in TOPPINGS:
Radiobutton(root, text=text, variable=pizza, value... |
7166fe9d7a1ce1172d5b2b2211aee6a840e7f74a | syurskyi/Python_Topics | /070_oop/001_classes/examples/Python 3 Most Nessesary/13.4. Listing 13.9. Multiple inheritance.py | 1,269 | 3.6875 | 4 | class Class1: # Базовый класс для класса Class2
def func1(self):
print("Метод func1() класса Class1")
class Class2(Class1): # Класс Class2 наследует класс Class1
def func2(self):
print("Метод func2() класса Class2")
class Class3(Class1): # Класс Class3 наследует класс Class1
def fu... |
151e93d8d8a7d6612011cca325e95b00f12aa4b0 | mylgood/myl_good_demo | /code/chapter04/17_高阶函数.py | 993 | 4.03125 | 4 | '''
def fun_a(callback):
"""
callback:function
"""
callback()
return 1
def fun_b():
print("fun_b")
fun_a(fun_b)
def fun_c():
print("fun_c")
return fun_b
ret = fun_c()
print(ret)
ret()
'''
# map 是一个映射, 接受两个参数,第一个参数是一个函数,第二个参数是序列(列表/元组)
# 返回值: 可迭代的对象 list(ret) 转换为序列
#需求: ... |
e94b66c585cd925cb6d4c8ae95216ac076937007 | aravinddhanasekar/bounceball | /bounceballmod.py | 1,605 | 4.09375 | 4 | from random import randint
import pygame
screen_height = 600
screen_width = 600
len_line = 80
num_lines = 7
speed = 0.1
start = 0
size = [screen_width, screen_height]
# colors
GREEN = (102, 255, 102)
BLACK = (0, 0, 0)
def generate_coords(num, from_bottom):
"""
coordinates will be generat... |
0ea9424e70701e9fd1d406fa9ad6cbcb1e0df10b | dust2907/HW_SkillUp | /Lesson 3-7/HW 3-7.py | 5,491 | 3.859375 | 4 | # ==========================
# ======= Задание 1 =======
# ==========================
class Car:
def __init__(self, **kwargs):
self.brand = kwargs.get('brand', None)
self.model = kwargs.get('model', None)
self.year = kwargs.get('year', None)
self.engine_volume = kwargs.get('engine_... |
04df3af76fb691e40f529518282bc92b05573f92 | MelaniePascullo/CS0008-f2016 | /f2016_cs8_mgp26_fp.py | 2,599 | 3.59375 | 4 | #
#
# name : Melanie Pascullo
# email : mgp26@pitt.edu
# class : CS0008-f2016
# instructor : Max Novelli
# Final Project
1
# example we had in class
"""# class definition
class definition
***participant class***
# properties
# methods
# initializer methods
def _init_(self,name,di... |
3935ef13b6fd070d31298514cb7df6e12a130096 | AdanVlpz7/Practica1EDA2 | /main.py | 2,612 | 3.984375 | 4 | import random
import math
from timeit import timeit
print("***** Practica 1 *****")
print("Este es un programa que tiene las funciones de BubbleSort, BubbleSort Optimizado y MergeSort")
def measure_time(func, *args, **kwargs):
globals_ = {'func': func, 'args': args, 'kwargs': kwargs}
time = timeit('func(*args... |
a5f17933fd282af1ae6b5e0c0dfb290413b3b3fe | insistlfy/pythonlearn | /python/oop/oop_05.py | 1,642 | 3.953125 | 4 | # !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@author:lfy
@file: oop_05.py
@time: 2021-04-14 下午2:53
@description: oop_05
面向对象三大特征 : 封装,继承,多态
-- 封装:
-- 继承: python支持多继承
-- 多态: 重写(子类重写父类的方法),重载(Py重载是通过可变参数来体现的,而且更方便)
-- 函数和方法的本质区别: 方法一定会有调用的主体(对象,类),而对象和类作为第一个... |
8ac5645960bc3459fc121f6d2cc3b6026c030d58 | DerekDongSir/Algorithms | /all_permutation.py | 670 | 3.765625 | 4 | from sys import argv
def all_permutation(ls,locate):
'''given a string ,output all the permutation answers'''
if locate == len(ls)-1: # 不需要进行交换,返回
return
else:
for i in range(locate+1,len(ls)): # 当前位置和之后位置的每一个进行一次交换
l = ls.copy() # 对当前列表进行拷贝,后续操作是对新列表的操作
l[locate],l[i... |
7f704e47b1db5388c3183f5d35df606f4d86913d | anjanshrestha622/py | /fiborinic.py | 316 | 3.796875 | 4 | Number= int(input("\n please enter the range of number:"))
i=0
first_value = 0
second_value = 1
while(i<Number):
if(i<=1):
next=i
else:
next= first_value + second_value
first_value = second_value
second_value = next
print(next)
i=i+1 |
d8ca4ae2596fa0748eb9906c335b0a509a345b95 | vrii14/PPL_Assignments | /Assignment_1/armstrong.py | 345 | 3.8125 | 4 | n1 = int(input("Enter starting number of the range: "))
print(type(n1))
n2 = int(input("Enter last number in the range: "))
armstrong = []
for i in range(n1, n2+1):
number = [int(d) for d in str(i)]
#print (number)
sum = 0
for j in number:
sum = sum + j**3
if sum == i:
armstrong.appe... |
09b57d09110d1eb6a63a84adc5cfdc7d05ed20cf | rcgalbo/advent-of-code-19 | /day4.py | 1,053 | 3.59375 | 4 | # day 4
from typing import List
from collections import Counter
input_range = [[int(i) for i in str(d)] for d in range(347312, 805915)]
# six-digit number
# password value is within given range of inigers
# digit i+1 >= i for digit in password=
def non_decreasing(password: List[int]) -> bool:
return all(i<=j for... |
99ed473a927dbf686edd8c9d308f22643c7e3a7c | ebarlas/tidemeter | /tideleds.py | 3,524 | 3.546875 | 4 | import math
class LedConfiguration():
def __init__(self, num_low_leds, num_high_leds, num_level_leds, min_led_level):
self.num_low_leds = num_low_leds
self.num_high_leds = num_high_leds
self.num_level_leds = num_level_leds
self.min_led_level = min_led_level
class TideLeds():
d... |
31ebdb0da1364c042ceca488855ea130c86814cb | oswaldo-mor/Tarea_03 | /Vector.py | 666 | 3.5625 | 4 | #Encoding: UTF-8(
#Autor: Oswaldo Morales Rodriguez A01378566
#Conociendo magnitud y angulo, graficar
from Graphics import *
def main():
magnitud=int(input("Magnitud"))
angulo=int(input("Angulo"))
t=Arrow((0,300),0)
dibujarPlano(t)
dibujarVector(magnitud,angulo,t)
def dibujarPlano(t):
v=Wi... |
f1c789a73e4fc102ce307828138421917d56bbd2 | jhfernan/Python-Playground | /Mike's Playground/3D_Vectors.py | 386 | 4.53125 | 5 | #Create a way to mathematically calculate 3-D vectors
import math
#Calculate the magnitude of a vector
def magnitude():
#Enter variable values
x = float(input('Enter x value.\n>>> '))
y = float(input('Enter y value.\n>>> '))
z = float(input('Enter z value.\n>>> '))
value = math.sqrt(x ** 2 + y **... |
ee3e107a0b6145915a5d30c10ac4b4f454192307 | ChrisMichael11/ds_from_scratch | /neural_networks.py | 6,815 | 3.515625 | 4 | from __future__ import division
from collections import Counter
from functools import partial
from linear_algebra import dot
import math, random
import matplotlib.pyplot as plt
import matplotlib
def step_function(x):
"""
Define step function for NN nodes
"""
return 1 if x >= 0 else 0
def perceptron_... |
11c5659761ee940ba7d788da59f779c265b71232 | stavitska/amis_python71 | /km71/Stavytska_Anastasia/task.7.py | 409 | 3.6875 | 4 | a1=int(input("введіть номер рядку першої клітини "))
b1=int(input("введіть номер стовпчика першої клітини"))
a2=int(input("введіть номер рядку другої клітини"))
b2=int(input("введіть номер стовпчика другої клітини"))
if (a1+b1)%2==(a2+b2)%2:
print("yes")
else:
print("no")
|
bc6b9249cba32810a367cb2da7475f241cf4196c | python101ldn/exercises | /Session_3/3e_lowest_highest_solution.py | 226 | 4.03125 | 4 | # Print the lowest and highest numbers in a list
numbers = [65, 4, 9, 23, 15, 875, 3.69, 33, 12, 79, 6]
sorted_numbers = sorted(numbers)
print("Lowest:", sorted_numbers[0])
print("Highest:", sorted_numbers[len(numbers) - 1])
|
c332007b2f13b89b4e71960ed394534cc06b3dac | jpc0016/Python-Examples | /Crash Course/ch2-Variables-and-Data-Types/name.py | 617 | 4.03125 | 4 | # Chapter 2 Strings
# Change capitalization of first letters
# using the title() method
name = "ada lovelace"
# print(name.title())
# Change string to all uppercase or all lowercase
# print(name.upper())
# print(name.lower())
# Concatenate Strings with "+"
# Don't forget the space!
first_name = "ada"
last_name = "lo... |
6ce1b1b43da5e77581fe70fc14433f57f86b5255 | krishnashah29/Incubyte | /string_calculator.py | 4,084 | 3.578125 | 4 | import unittest
class Tests_StringCalculator(unittest.TestCase):
def test_EmptyString_return_0(self):
self.assertEqual(StringCalculator.Add(""),0)
def test_SingleNumber(self):
self.assertEqual(StringCalculator.Add("1"),1)
self.assertEqual(StringCalculator.Add("2"),2)
def te... |
a88ed3d2f14e46e015df45454aa43c16953c5c73 | HamzaBhatti125/Python-Programming | /CP-project/combination.py | 409 | 4 | 4 | def fact(x):
if x==1:
return 1
else:
return x * fact(x-1)
n=int(input('enter first number: '))
r=int(input('enter second number: '))
def com(n,r):
if n<0 or r<0:
print('please enter positive number')
else:
combination=(fac... |
8118eb7e30bda46f1038a1e46211cec42005d67e | itwebMJ/algorithmStudy | /Lv0__16_to_30/20.K번째수.py | 1,017 | 3.546875 | 4 | '''
K번째수
배열 array의 i번째 숫자부터 j번째 숫자까지 자르고 정렬했을 때, k번째에 있는 수를 구하려 합니다.
예를 들어 array가 [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, k = 3이라면
array의 2번째부터 5번째까지 자르면 [5, 2, 6, 3]입니다.
1에서 나온 배열을 정렬하면 [2, 3, 5, 6]입니다.
2에서 나온 배열의 3번째 숫자는 5입니다.
배열 array, [i, j, k]를 원소로 가진 2차원 배열 commands가 매개변수로 주어질 때,
commands의 모든 원소에 대해 앞서 설명한 연산을 적용했... |
465d09a0ffc033e0bef6d63f46c0aae61eeab969 | duochen/Python-Beginner | /Lecture01/Exercises/list_methods.py | 2,905 | 4.21875 | 4 | # Make a list
users = ['val', 'bob', 'mia', 'ron', 'ned']
# Get the element
first_user = users[0] # first element
second_user = users[1] # second element
newest_user = users[-1] # last element
# Modify individual items
users[0] = 'valerie' # change an element
users[-2] = 'ronald'
users.append('a... |
5f71a3def50a8978b589c25f155a30e850183c90 | gpapple/Python1 | /body/pachong/Purl.py | 445 | 3.53125 | 4 | '''
大致流程是:
1. 利用data构造内容,然后urlopen打开
2. 返回一个json格式的结果
3. 结果就应该是girl的释义
'''
import requests
import json
word = input('please enter:')
url = 'https://fanyi.baidu.com/sug'
data = {
'kw':word
}
headers = {
'ContentLength':str(len(data))
}
rsp = requests.post(url,data=data,headers=headers)
# print(rsp.json())
for i ... |
3617c90e28b725c41404870658685fee060ccf4f | abbywong/learning | /begin/faculty_recursive.py | 255 | 3.765625 | 4 |
"""
Here is another solution of the faculty problem. Can you understand it?
"""
def faculty(n):
if n <= 1:
return 1
previous = faculty(n - 1)
return n * previous
print('faculty:')
print(4, faculty(4))
print(6, faculty(6))
print(9, faculty(9))
|
87071adbb7d56a4bca5ce41095e2d8c363a90466 | thanhtd32/advancedpython_part1 | /Exercise14.py | 1,147 | 3.5625 | 4 | #Coder: Tran Duy Thanh
#Email: thanhtd@uel.edu.vn
#Phone: 0987773061
#Blog for self-study: https://duythanhcse.wordpress.com
#Facebook for solving coding problem: https://www.facebook.com/groups/communityuni
def frequency(toiecScores):
counters=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for toiecScore in toiecScores... |
88bcd35535c59a2a2da7b5c79e32578818e5d533 | KGHuntley/CYOA-EKOO | /Beta game.py | 2,796 | 4.40625 | 4 | # Choose.py
# by Kyal,
# Description: starter code for the Choose Your
# Own Adventure Project
# Import Statements
from tkinter import *
import tkinter.simpledialog
import tkinter.messagebox
root = Tk()
w = Label(root, text="Choose Your Own Adventure")
w.pack()
def intro():
""" Introductory Function -> starts t... |
2caa216de3fcf4271b52c5cdf671ae241922cf5d | khollbach/alpha_o | /src/main/color.py | 1,294 | 4 | 4 | #!/usr/bin/python3
from enum import Enum
class Color(Enum):
'''
Represents the colors a tile can be: none (unknown), white, or black.
'''
none = 0
white = 1
black = 2
def __str__(self):
'''(Color) -> str
Print a single-character representation of the color.
>>> s... |
8746a131891120a3b2efd9ed4fe68612743c8d64 | vivianLL/LeetCode | /1071_GreatestCommonDivisorofStrings.py | 1,726 | 3.953125 | 4 | '''
1071. Greatest Common Divisor of Strings
Easy
https://leetcode.com/problems/greatest-common-divisor-of-strings/
For strings S and T, we say "T divides S" if and only if S = T + ... + T (T concatenated with itself 1 or more times)
Return the largest string X such that X divides str1 and X divides str2.
'''
... |
b8f374e39ea5f9e81719f5782d6a1566d936a426 | sogada/python | /ex44b.py | 366 | 4.0625 | 4 | class Parent(object):
def override(self):
print "PARENT override()"
class Child(Parent):
#This replaces the functionality of the function of the same name
#in the class behing inherited by Child, which is Parent in this case
def override(self):
print "CHILD override()"
dad = Parent()... |
e89d45a486ba1d42bc4116af6842ad84fa26dfbe | Maryvictor/exercicios-python | /teste 4.py | 1,046 | 3.71875 | 4 | print ("Código Especificação Preço")
print (" 1 Salgado R$4,00")
print (" 2 Cachorro Quente R$6,00")
print (" 3 Hamburguer R$8,00")
print (" 4 X Burguer R$10,00")
print (" 5 Refrigerante R$4,50")
total = float(0)
cont = str("Sim")
i = int(1)
print(input("Deseja fazer um pedid... |
21e7b5839c1c1016da6436671245792b5ea09bbd | 8v10/eprussas | /1_LogicaDeProgramacao/0_Python/3_Python_Parte3/9 - Expressões Regulares/3 ER - split.py | 184 | 4.21875 | 4 | import re
#Check if the string starts with "The" and ends with "Spain":
str = "O Rio de Janeiro continua lindooo"
x = re.split("\s", str)
print (str)
print(x)
print(x[1:4])
|
09f3e623afbf9e5da23deb89890a372537b373f3 | dackJavies/Neuroscouting-Problem | /tree_problem.py | 5,313 | 3.828125 | 4 | # Tree problem solution by Jack Davis for Neuroscouting interview
class Node:
def __init__(self, position, value, depth):
self.position = position
self.value = value
self.depth = depth
self.lft_nbor = None
self.rgt_nbor = None
self.left = None
self.right = ... |
33c2d76a9ed0808e37ff60c728521e787c4fd7d9 | 8woodcockd/agent-based-model | /agentframework.py | 7,695 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 22 10:46:55 2018
@author: Dean
"""
import random
import math
class Agent:
def __init__(self, environment, agents, rows, cols):
"""Assign attributes to each agent.
"""
self._x = random.randint(0,cols-1)
self._y = random.randint(... |
1f9f670789d8feda5b577f45928d9a26b8378711 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4443/codes/1808_2575.py | 296 | 3.671875 | 4 | from numpy import *
pref = array(eval(input("Digite uma das opcoes TV Netflix Youtube: ")))
vs = zeros(3, dtype=int)
for i in range(size(pref)):
if(pref[i] == "TV"):
vs[0] = vs[0] + 1
elif(pref[i] == "NETFLIX"):
vs[1] = vs[1] + 1
elif(pref[i] == "YOUTUBE"):
vs[2] = vs[2] + 1
print(vs) |
0190539e2f16950078f9cdc2f2bd24247b105369 | Roc-J/jianzhioffer | /problem029.py | 517 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: qjk
import heapq
class Solution:
def GetLeastNumbers_Solution(self, tinput, k):
# write code here
if k > len(tinput) or k == 0:
return []
heaq = []
for i in tinput:
heapq.heappush(heaq, i)
result... |
824762ef869cf64b2552bbc9b2d06af284273a35 | Protino/HackerRank | /Contests/Week of Code 23/lighthouse.py | 1,309 | 3.59375 | 4 | import math
n = int(input())
max_possible = n//2-(1)*(n%2==0)
arr = []
def format_input():
for __ in range(n):
line = input()
in_arr = []
for ch in line:
if ch=='*':
in_arr.append(0)
else:
in_arr.append(1)
arr.append(in_arr)
d... |
bc3720aaef8fb4180ec1185d76e652d59cc09f74 | Arulselvam5006/training-n | /vowvels.py | 161 | 4 | 4 | str = input("")
if str in ('A', 'E', 'I', 'O', 'U','a','e','i','o'):
print("%s is a vowel." % str)
print("vowel")
else:
print("%s is a consonant." % str)
|
f0637b161936f88fd5bf1b980f6dbc7be41f7f72 | naveenkumar2703/Miscellaneous | /Calculator.py | 2,816 | 4 | 4 | from __future__ import print_function, division
import cmd
class Calculator(cmd.Cmd):
prompt = 'calc >>> '
intro = 'Simple calculator that can do addition, subtraction, multiplication and division.'
def do_add(self, line):
args = line.split()
total = 0
for ... |
f4836fb60c0936eee4a4d3ecc054f14a1f4f915c | johnhany97/CCI-solutions | /chapter1/1-isUnique.py | 2,245 | 4.15625 | 4 | import unittest
# is_unique
#
# Used to check if a string is fully constituted of unique characters
# As in, no characters are repeated.
#
# params:
# s: string
#
# returns:
# boolean
#
# runtime:
# O(n) where n is the length of the string
#
# space complexity:
# O(c) where c is each character in the string
def is_un... |
df14323c0b2c95f887bb9455129f10524bf13e2c | klysman08/Python | /map_reduce_lambdas/lambdas.py | 585 | 4.28125 | 4 | from functools import reduce
# List of students with their names and grades
alunos = [
{'nome': 'João', 'nota': 5.0},
{'nome': 'Maria', 'nota': 7.0},
{'nome': 'José', 'nota': 8.0},
{'nome': 'Ana', 'nota': 9.0},
{'nome': 'Pedro', 'nota': 10.0}
]
# Lambda function to check if a student's grade is gr... |
d3ef6829040467883cec8bcd30667653c8ee0afd | pinard/FP-etc | /scripts/rmdir-empty | 812 | 4 | 4 | #!/usr/bin/env python3
# Copyright © 2000, 2003 Progiciels Bourbeau-Pinard inc.
# François Pinard <pinard@iro.umontreal.ca>, 2000.
"""\
Remove empty directories in the given directory hierarchies.
Usage: rmdir-empty [DIRECTORY]...
If not directory is given, the current directory is implied.
"""
import os
import sys... |
deb05dc21e116ecbe061a4e4175c99514854a9e1 | JuhiSrivastava/Data-Structures | /C2 - Week1/tree1.py | 1,176 | 3.578125 | 4 | #Python3
#week -1 - assign2
import sys, threading
sys.setrecursionlimit(10**7) # max depth of recursion
threading.stack_size(2**27) # new thread will get stack of such size
def ComputeHeight(maxiheight,li,a,count,current):
if len(li) == 0:
return maxiheight,li,a,1
if li.get(current) == None:
re... |
0b17d3cc39fd6d42af88442b9c17e1f9a0b7dc52 | alukinykh/python | /lesson1/1.py | 259 | 4.0625 | 4 | years = 15
name = input('Введите имя ')
surname = input('Введите фамилию ')
age = int(input('Введите возраст '))
print(name, surname, f'{age} лет')
print(f'Через {years} лет вам будет {age + years}')
|
ed294deefd026cd095603a289f6dff9b07c6efab | mets18/python-challenge | /PyBank/main.py | 2,726 | 3.796875 | 4 | # import dependencies
import os
import csv
# convert csv
budgetcsv = os.path.join ("resources","budget_data.csv")
# Read in file and split the data
with open(budgetcsv, 'r') as csvfile:
data = csvfile
csvreader = csv.reader(data, delimiter=',')
# The total number of months included in the dataset
row_cou... |
db1451d892cc5c9aab427fec478baf2ba1b5aede | jiinmoon/Algorithms_Review | /Archives/Leet_Code/Old-Attempts/0453_Minimum_Moves_to_Equal_array_Elements.py | 1,227 | 3.6875 | 4 | """ 453. Minimum Moves to Equal Array Elements
Question:
Given an non-emptry array, find the minimum number of moves to bring every
element to eual another. A single move is incrementing n-1 elements by 1.
+++
Solution:
[1, 4, 3, 2]
The minimum number of moves have be depend upon the minimum of th... |
7dbaacbd91e7f224eae630ff25a9b0763563bb15 | WistyDagel/PyFrac | /UserDialogue.py | 986 | 3.890625 | 4 | from Fraction import Fraction
class UserDialogue:
def __init__(self):
self.f1 = None
self.f2 = None
self.result = Fraction(0, 0, 1)
def retrieveFraction(self):
whole = int(input("Please Enter a Whole Number: "))
num = int(input("Please Enter a Numerator: "))
... |
4f74cdcbb83322bdb4618580fae1621a8bd29201 | daigo0927/ProgrammingContest | /AtCoder/ABC043/ProbB.py | 154 | 3.515625 | 4 | s = input()
ans = ''
for ss in s:
if ss == '0':
ans += '0'
elif ss == '1':
ans += '1'
else:
ans = ans[:-1]
print(ans)
|
bbd7f9672dcf3b25688349c4668d0e485672956a | pgadds/Program-Design-and-Abstraction | /Problem Set 3.py | 3,710 | 4.15625 | 4 | import random
def loadWords():
WORDLIST_FILENAME = "words.txt"
print("Loading word list from file...")
inFile = open(WORDLIST_FILENAME, 'r')
line = inFile.readline()
wordlist = line.split()
print(" ", len(wordlist), "words loaded.")
return wordlist
def chooseWord(wordl... |
1b686bf04b8a158aded5c6dcc52326618cd97aaa | xuzewei28/ml-project-1-cwx | /implementation.py | 7,015 | 3.640625 | 4 | import numpy as np
from numpy import linalg
np.random.seed(0)
def compute_loss(y, x, w):
"""Calculate the loss using mse."""
error = y - x.dot(w)
return np.sum(np.power(error, 2)) / (2 * len(y))
def compute_gradient(y, x, w):
"""Compute the gradient."""
error = y - x.dot(w)
... |
2671b96f995d2692f61be3525cf05495356a0658 | saloneeshah/Final-Project | /temp_work_files/temp_file_Speed and Reaction time.py | 1,981 | 3.59375 | 4 | #The program calculates the probabiliy that the goalie actually save the ball when he/she gets the direction right
#the variables and threshold are subject to change
import numpy as np
import math
def fail_or_succeed(goalie_reaction_time, ball_speed, kick_angle):
goalie_reaction_time = np.random.normal(0.0... |
c7f728c9d455ae315f171d0f9efed9da20e4e144 | karthikh07/Python-core | /Basics/loops.py | 116 | 4 | 4 | n = int(input('enter Number for factorial: '))
res=1
for fact in range(n,1,-1):
res = res*fact
print (res)
|
db9dbf15977560379b980c3030749d379551069c | sandipgole/BasicPython | /14_WeightConverter.py | 234 | 4 | 4 | weight=int(input("weight plz"))
unit=input("kg or gram")
if unit.upper() == "KG":
converted = weight*1000
print(f"weight in gram {converted}")
else:
converted=weight/1000
print(f"weight in kg {converted}")
|
0e86c647e79b7624e06d59cf68253b12077f595c | SilverBlaze109/VAMPY2017 | /projects/guessing_game.py | 449 | 3.984375 | 4 | lower = 0
upper = 0
guess = 1
ans = ""
while ans != "YEPP":
ans = input("Is "+str(guess)+" your number, or is it more or less than your number? (YEPP/LESS/MORE): ")
if ans == "MORE":
if upper == 0:
guess *= 2
else:
lower = guess
guess = int((lower + upper)/2)
elif ans == "LESS":
if upper == 0:
lowe... |
4a98b9fb9ee98be202c74433c0784b4f7cc755ce | TESTUDENT101exe/CompSciHW | /Models and simulations/HopeTopia Utopia.py | 1,403 | 3.9375 | 4 | import matplotlib.pyplot as plt
import math
from random import randint as rand
population=175
Male=84
Female=91
possible_birth=0.6
birth_rate=0.3
starvation_rate_baseline=0.001
resources=100000
resource_end=1
Gender=0.5
death_rate=0.05
x_coords = []
y_coords = []
for i in range(0, 250):
if populat... |
7c8f0d9a8c36d192cd4fc39573f9a89c2d62e052 | miniaishwarya/Python-stuff | /schoolofaiassignment.py | 2,304 | 3.875 | 4 | with open("data.csv.txt",'r') as file:
file_data=file.read()
print('Processing done.')
#print(file_data)
file_data_lines = file_data.split('\n')
#print(file_data_lines)
# Splitting induvidual lines.
# The original string representation.
#print(file_data_lines[1])
# The String split into different... |
aeb918e17005e1b086a10e6c5fc87f3c936c4ff9 | NikhilMJain/PCCode | /One/treeviews.py | 771 | 3.671875 | 4 | class Node():
def __init__(self, info = None):
self.info = info
self.l = self.r = None
one = Node(1)
two = Node(2)
three= Node(3)
four = Node(4)
five = Node(5)
one.l = two
one.r = four
two.l = three
two.r = five
def leftprofile(root):
if root:
print root.info
if root.l:
... |
4a88bab8b0bd90089aeaa463ef416f67fc40f6e8 | aubreybaes/DataStructures2018 | /ImSimpleCalculator.py | 1,517 | 4.21875 | 4 | #Simple Calculator
#Mae Aubrey C. Baes
#github.com/aubreybaes
#maeaubrey.baes@gmail.com
#This program performs the four basic arithmetic operations
print ("WELCOME to CALCULATOR!")
def on():
opera = input("\n\n ENTER THE OPERATION YOU WANNA USE! \n 1. ADDITION \n 2. SUBTRACTION \n 3. MULTIPLICATION \... |
da3a7a2564ebe84e94272213f7b5d9297b17c8d0 | phillybenh/Intro-Python-I | /src/13_file_io.py | 948 | 4.3125 | 4 | """
Python makes performing file I/O simple. Take a look
at how to read and write to files here:
https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
"""
# Open up the "foo.txt" file (which already exists) for reading
# Print all the contents of the file, then close the file
# Note: pay close... |
05a7702e34e5dad9ee1e737e86c688a619a7ae93 | s-vedara/Python-Lessons | /test.py | 1,074 | 4.125 | 4 | ##Зададим переменные.
DBPASS = "FSxBo~W$Rr1{"
print(DBPASS)
print(3 + 4); print(3 * 5); print(3 ** 2)
Wname = "denis"
print(Wname)
print(Wname.title()) #Сделать первую букву заглавной
print(Wname.upper()) #Сделать все буквы заглавными
print(Wname.lower()) #Сделать все буквы маленькими
#print(Wname.rstrip())... |
449d81ed68c5b4d65b0f9abfaf05d099c54ad028 | tuckerrking/intro_to_cs_projects | /Chap_9_Lab.py | 1,140 | 4.5 | 4 | # This program asks the user to enter 20 names, separated by commas,
# into a string array,
# then sorts that array in alphabetical order and displays
# its contents.
# The program uses the "bubble sort" method.
# Funtion gets user input
def get_user_input():
list_of_names = []
separator = ","
list_of_name... |
43a14459fe490daef3e0388174104bce3abfa758 | talitagiovanna/listas-IP | /20.2L5Q2 - Árquipelago Recursional.py | 1,100 | 4.03125 | 4 | ilha_atual = int(input())
ilha_desejada = int(input())
suprimento = int(input())
def recursional(ilha_inicial, ilha_tesouro, contador):
if contador == suprimento and ilha_inicial == ilha_tesouro:
#print("Já estamos aqui, marujo!")
return "Já estamos aqui, marujo!"
elif ilha_inicial == ilha_te... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.