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 |
|---|---|---|---|---|---|---|
5c12a749074258c3adc63a9a47a68692fb1739ee | IMAYousaf/Typing_Speed | /main.py | 1,317 | 3.859375 | 4 | import random
import time
import difflib
def main():
choice = input("Type in \"EASY\" or \"HARD\" based upon your desired difficulty level:")
if choice in {"EASY", "easy"}:
text = open("The_Arabian_Nights.txt").readlines()
selection = random.choice(text).strip()
word_count = len(selecti... |
077340fff43e14d6eafcd347accd28ca528d59b1 | minh-quang98/nguyenminhquang-fundamental-c4e20 | /Session01/Homework/converst_ex.py | 96 | 3.5625 | 4 | Cel = int(input("Enter the temperature in celsius?"))
Fah = Cel * 1.8 + 32
print(Cel, "=", Fah) |
f744d47fb116c2b92bfaa60a991a6c3b8e554a7d | kishirasuku/atcoder | /arc/002/b.py | 835 | 4.09375 | 4 | import calendar
def main():
today = raw_input()
today = today.split("/")
today = [int(s) for s in today ]
year,month,day = today
while True:
if daycheck(year,month,day):
print str(year) + "/" + format(int(month),'02d') + "/" + format(int(day),'02d')
break
... |
ae9cf8951de63c7f987f003eb9f492b9227c650a | udaykd09/Algorithms | /PowerSet.py | 450 | 3.71875 | 4 | def getSubsets(set, index=0):
allSets = []
if len(set) == index:
allSets.append([])
else:
allSets = getSubsets(set, index+1)
item = set[index]
moreSubsets = []
for subset in allSets:
newSubset = []
newSubset += subset
newSubset.appe... |
7e2f2b668467c044f634a4fa128650bdf4bebd91 | ricardorosa-dev/Curso-Trybe | /35.2_entrada_saida_arq/ex01.py | 93 | 3.859375 | 4 | nome = input("Qual é o seu nome?")
for letter in range(len(nome)):
print(nome[letter])
|
9de922ad0f8821a055959782334a797ff49f9c5e | texrer/Python | /CIS007/Lab1/Lab1_PrintFormat_RichardRogers.py | 104 | 4 | 4 | print("a a^2 a^3")
for x in range (1,5):
print (format(x, "<5d"), format(x**2, "<7d"), x**3) |
4097ed53e7d899e9518a2ca15ad7136361704f61 | thomasren681/MIT_6.0001 | /ps4/ps4b.py | 12,673 | 3.828125 | 4 | # Problem Set 4B
# Name: Thomas Ren
# Collaborators: None
# Time Spent: About 3 hours
import string
### HELPER CODE ###
import numpy as np
def load_words(file_name):
'''
file_name (string): the name of the file containing
the list of words to load
Returns: a list of valid w... |
dc7a8b03fe4a24ae53d659b0a68d3230596af6e6 | varma1096/Python--CSEE5590-490 | /icp1/r1.py | 442 | 3.984375 | 4 | import random
gen_num = random.randint(0, 9)
while (1):
i_num = int(input('Enter a number which is in range of 0 to 9'))
if(gen_num == i_num):
print('perfect , guessed mumber is equal to the generated number')
break
elif(gen_num < i_num) :
print (' your number is greater than gener... |
62f1913eda6e5f9985be25d62f7b16de82a94d74 | Gliklex/YPetrov_10_02_02 | /task_10_02_02_pizza.py | 5,345 | 3.59375 | 4 | # Программирование на языке высокого уровня (Python).
# https://www.yuripetrov.ru/edu/python
# Задание task_10_02_02.
#
# Выполнил: Фамилия И.О.
# Группа: !!!
# E-mail: !!!
class Пицца:
"""Класс Пицца содержит общие атрибуты для пиццы.
Дочерние классы будут их конкретизировать.
"""
def __init__(sel... |
6e6efa2cd5c9dbcee684fbcd710d1ea0e508bbc7 | aadhi24/my-python-codes | /project 2 (tip calculation).py | 498 | 4 | 4 | #this code written by aadithyan
print("welcome to tip calculator")
bill_amount = float(input("what is the total bill? $"))
percentage_tip =float(input("what percentage tip would you like to give? 10 , 12 or 15 "))
split_bill = int(input("how many people to split the bill? : "))
per_tip = percentage_tip /100
mult_... |
52df5ce0e9041403fcb78412bed84f68fd8cd53d | facaiy/book_notes | /leetcode/knapsack_0_1.py | 724 | 3.65625 | 4 | #!/usr/bin/env python
import numpy as np
def knapsack(data, max_weight):
if not data: return None
rows = max_weight + 1
cols = len(data[0]) + 1
dp = np.zeros((rows, cols))
for w in range(1, rows):
for n in range(1, cols):
id_ = n - 1
if data[0][id_] > w:
... |
ba67e4c4674f5099fa6d6fadebbc1a7f46634e34 | Ronnieyang97/notes | /py_training/most-far-can-reach.py | 1,294 | 3.59375 | 4 | # .机器人的运动范围
# 题目:地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,
# 但是不能进入行坐标和列坐标的数位之和大于k的格子。请问该机器人能够达到多少个格子?
def farest(m, n, k): # 获取棋盘的大小,和k的大小
m, n = str(m), str(n)
x, y = '', ''
loc_m, loc_n = 0, 0
while k > 0 and loc_m < len(m) and loc_n < len(n):
if int(m[loc_m]) + int(n[loc_n]) ... |
e780d7256717917f5d769ba68218068a244d28ed | foTok/data_driven_diagnosis | /bpsk_navigate/msg_generator.py | 765 | 3.59375 | 4 | """
this module generate msg randomly
"""
import fractions
import numpy as np
class Msg:
"""
Msg generate msg randomly
"""
def __init__(self, code_rate=None, sample_rate=None):
self.code_rate = 1023000 if code_rate is None else code_rate
self.sample_rate = self.code_rate * 10 if sample... |
5724e2d7f2e36197df1d1ff332b18e1d04277db1 | ctefaniv/Homework | /HW7/cw1.py | 272 | 3.765625 | 4 | def count_positives_sum_negatives(arr):
positives = []
negatives = []
for i in arr:
if i > 0:
positives.append(i)
elif i < 0:
negatives.append(i)
return [len(positives), sum(negatives)] if arr != [] else [] |
aa82ac04921b5ccd2ecdfb3d78f9c13dc4b18ba7 | wizardshowing/pyctise | /cal_evaluator.py | 2,053 | 3.765625 | 4 | #
# This is an example of how to evaluate expressions
#
class ExpNode(object):
def __init__(self, name, left, right):
self.name = name
self.left = left
self.right = right
def _evaluate_child(self, child):
if child:
return child.evaluate()
else:
... |
7804dbebe2f68198efbff2ac189edb06a1631fec | AKASHRANA931/Python-Program-Akash-Rana- | /add.py | 88 | 3.796875 | 4 | a = int(input("Enter the number"))
b = int(input("Enter the number"))
p = a + b
print(p) |
2fde54c4ca1d41c52ae10af5041fa5f7ed31dd6b | Chaitalk-csk/test | /hungry.py | 123 | 4.03125 | 4 | r = input("are you hungry? answer yes or no?")
if r == "yes":
print("Eat Pav bhaji!!")
else:
print("do your work")
|
ce61eb9622e047c217b5d8ce56066aba325b05d7 | CodingMarathon/All_Algorithm | /HMM/hmm.py | 10,573 | 3.71875 | 4 | """
@author:CodingMarathon
@date:2020-03-18
@blog:https://blog.csdn.net/Elenstone/article/details/104902120
"""
from typing import List, Any
import numpy as np
import random
class HMM(object):
def __init__(self, n, m, a=None, b=None, pi=None):
# 可能的隐藏状态数
self.N = n
# 可能的观测数
... |
ad0a43440ee229ebf6a918b63f72205f06d63409 | araschermer/python-code | /algorithms_and_data_structures/linked_lists/remove_nth_element.py | 1,289 | 4.375 | 4 | from linked_lists_util import print_linked_list, insert_list, Node
class LinkedList:
def __init__(self):
self.head = None
def remove_nth_node_from_end(self, n: int):
"""Removes the node at the nth position from the end of the linked list."""
pointer1 = self.head
pointer2 = sel... |
c50da511eb3a90f61e8003ec59f7b4f4b9f32fe8 | fdm1/Euler | /python/solved/01.py | 419 | 3.78125 | 4 | # /*************************************
# *
# * Find the sum of all the multiples of 3 or 5 below 1000
# *
# **************************************/
import time
from functools import reduce
start_time = time.time()
nums = list(filter(lambda x: x % 3 == 0 or x % 5 == 0, range(0,1000)))
res = reduce(lambda x,y: x + ... |
63ac37df5e490e1d2ebd6933986c9555b189bd92 | fishla1202/hometest | /q1.py | 284 | 3.765625 | 4 | def fib(n):
f = dict()
f[0] = 1
f[1] = 1
f[2] = 2
if n == 0 or n == 1:
return 1
elif n == 2:
return 2
for i in range(3, n + 1):
f[i] = f[i - 1] + f[i - 2] + f[i - 3]
return f[n]
if __name__ == '__main__':
print(fib(5))
|
5004c69f8b7a2a22c952482a9db1c06773b5c1b4 | cnlong/everyday_python | /06_day_important-word/test3.py | 1,150 | 3.65625 | 4 | from collections import Counter
import re
import string
import os
def get_word(txtFile):
'''
从一个txt文件中找出出现次数最高的词及其对应次数,以元组形式返回
'''
# 过滤词
stop_word = ['the', 'in', 'of', 'and', 'to', 'has', 'that', 'this', 's', 'is', 'are', 'a', 'with', 'as', 'an']
f = open(txtFile, 'r', encoding="UTF-8")
... |
901d488e2bd0a60b19c245e20da0d1c4d13e7001 | danong/leetcode-solutions | /solutions/longest_repeating_character_replacement.py | 944 | 3.578125 | 4 | """https://leetcode.com/problems/longest-repeating-character-replacement/description/"""
from collections import defaultdict
class Solution:
def characterReplacement(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
if not s:
return 0
c... |
4701acc8e7509159cefe8c87a50657059e090a49 | JhonEddi/Repaso-de-pyhon | /ejercicio 80.py | 92 | 3.703125 | 4 | def fibonacci (n):
if n<=2:
return 1;
if n>2:
return fibonacci(n-1)+fibonacci(n-2) |
8bdf9d4ac5cf8550415016a5d7f7bb7923b0c684 | vito-dante/Days-Boring | /python_examples/fibonacci.py | 402 | 4.0625 | 4 |
# def fibonacci(number: int) -> int:
# if(number <= 1):
# return 1
# else:
# return fibonacci(number - 1) + fibonacci(number - 2)
# print(fibonacci(9))
from typing import Iterator
def fib(n: int) -> Iterator[int]:
a,b = 0,1
while a<n:
yield a
a, b = b, a + b
for ite... |
86cef72772541d7f5650e1a2df1c63e871635a17 | uycuhnt2467/-offer | /從尾到頭列印list.py | 731 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 8 15:31:51 2021
@author: a8520
"""
# 是否能改變原始list?
# 後進先出 -> stack
class Node():
def __init__(self, val, next_ = None):
self.val = val
self.next= next_
def hasNext(self):
if (self.next) == None:
return False
else:
... |
6cf3cdc83b1e001d2f4ff275f489dfa035452986 | theunkn0wn1/uci-bootcamp-2021 | /uci_bootcamp_2021/examples/mistaking_equality_for_assigment.py | 785 | 4.0625 | 4 | """
uci_bootcamp_2021/examples/mistaking_equality_for_assigment.py
Demonstrates the common beginner error of mistaking `==` equality for `=` assignment.
WARNING: this file will not run and nor should it be used in any downstream applications,
as it contains intentionally invalid syntax.
"""
# NOTE: Do not mistake th... |
1d746c2dc234ecb6ac17952f30adf04f4ba49689 | JaksoSoftware/jakso-ml | /jakso_ml/utils/rect_utils.py | 355 | 3.828125 | 4 | def intersection(r1, r2):
'''
Intersection of two rectangles
'''
x1, y1, w1, h1 = r1
x2, y2, w2, h2 = r2
x = max(x1, x2)
y = max(y1,y2)
w = min(x1 + w1, x2 + w2) - x
h = min(y1 + h1, y2 + h2) - y
if w <= 0 or h <= 0:
return (0, 0, 0, 0)
return (x, y, w, h)
def area(r):
'''
Area of a re... |
a1d6f11a72622f75207f88599ab6a486203d7b96 | shirleymramirez/ProblemSet2_PayingDebtOffInAYear | /ProblemSet2_PayingDebtOffinaYear.py | 869 | 4.375 | 4 | outstandingBalance = float(raw_input('Enter the outstanding balance on your credit card: '))
annualInterestRate = float(raw_input('Enter the annual interest rate as a decimal: '))
""" Calculates the minimum fixed monthly payment needed in order to pay off credit card balance within
12 months. Not Dealing with a min... |
54d5fc3467314edadf86700b688043b6ca539400 | eneajorgji/programowanieObiektowe | /wyklad_2.py | 830 | 3.578125 | 4 | class Auto:
licznik = 0
def __init__(self, silnik, rok, marka): # self odnosi sie do obiektu
self.silnik = silnik
self.rok = rok
self.marka = marka
self.public, self._protected, self.__private = 8, 10, 20
Auto.licznik += 1
def __del__(self):
Auto.licznik -=... |
9b0b36fd3400269cf662c11b322b7fc8b08ece13 | eduard-netsajev/Personal-Practice | /Python/Games/2ndDrawing.py | 2,583 | 3.765625 | 4 | __author__ = 'Netšajev'
import random
import math
import pygame
pygame.init()
# Define some colors
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
GREEN = ( 0, 255, 0)
RED = ( 255, 0, 0)
BLUE = ( 0, 0, 255)
pi = 3.141592653
size = [700, 500]
screen = pygame.display.set_mode(size)
... |
ffef9333bf3de98de111bea5e89167b4ce7abbc6 | mauleypeach/pythonthehardway | /learnpythonthehardwayorg/ex.py/ex17.py | 643 | 3.625 | 4 | from sys import argv
from os.path import exists
script, from_file, to_file = argv
print "Copying from %s to %s" % (from_file, to_file)
in_data = open(from_file).read()
print "The input file is %d bytes" %len(in_data)
print "Does the output file exist %r" % exists(to_file)
print "Does the input file exist %r" %exis... |
84bdbbff05f16c1fdf99e58696e64992efd84bdb | here0009/LeetCode | /Python/1540_CanConvertStringinKMoves.py | 2,881 | 3.9375 | 4 | """
Given two strings s and t, your goal is to convert s into t in k moves or less.
During the ith (1 <= i <= k) move you can:
Choose any index j (1-indexed) from s, such that 1 <= j <= s.length and j has not been chosen in any previous move, and shift the character at that index i times.
Do nothing.
Shifting a chara... |
1648870dd600b282f7d08cd0ca262a239592f1cf | nena6/Python-Tutorial | /exercises_10.py | 1,969 | 3.6875 | 4 | import string
#Exercise 1
fname = input('Enter a file name: ')
try:
myfile = open(fname)
except:
print('File cannot be opened.')
exit()
words = []
senders = dict()
for line in myfile:
if not line.startswith('From'):
continue
words = line.split()
if len(words) > 2:
senders[wor... |
5cc32150ae561a890f85589723a57e9603467cdf | rLoopTeam/eng-embed-sim | /code_samples/tkinter/tkinter_grid_matplotlib.py | 1,914 | 3.53125 | 4 | # @see http://www.tkdocs.com/tutorial/grid.html
#from Tkinter import *
import ttk
import Tkinter as tk
root = tk.Tk()
content = ttk.Frame(root)
frame = ttk.Frame(content, borderwidth=5, relief="sunken", width=600, height=300)
namelbl = ttk.Label(content, text="Name")
name = ttk.Entry(content)
onevar = tk.BooleanVar... |
e03f35ac1bd806baaf86dfc1249b7e77cdc71e8d | huyquangbui/buiquanghuy-fundamental-c4e23 | /session2/hw/se1.py | 331 | 4.0625 | 4 | h = int(input("your height in cm: "))
h1 = h/100
print("which is",h1,"in m")
w = int(input("your weight in kg: "))
BMI = w/h1**2
if BMI < 16:
print("severly underweight")
elif BMI < 18.5:
print("underweight")
elif BMI < 25:
print("normal")
elif BMI < 30:
print("overweight")
else:
print("obese")
p... |
5911aa7ac34e627253367cdd4925f1aff96605d7 | Gunnstein/fastlib | /fastlib/_template.py | 3,303 | 3.71875 | 4 | # -*- coding: utf-8 -*-
import string
__all__ = ["TemplateStringFormatter", "TemplateFileFormatter"]
class TemplateStringFormatter(object):
fmt_dict = {}
def __init__(self, template_str):
"""Use a template from a string
Load a template string and substitute the
template keys with pr... |
026beb0b9c6f43099f5f641e0efc485476fdef42 | ealexisaraujo/basicoPython | /dictionary_comprehension.py | 596 | 3.84375 | 4 | # -*- coding: utf-8 -*-
def listComprehension():
pares = []
for num in range(1, 31):
if num % 2 == 0:
pares.append(num)
print(pares)
def comprehension():
even = [num for num in range(1, 31) if num % 2 == 0]
print(even)
def cuaddrados():
cuadrados = {}
for n... |
27684781cc1a1ca2797ffa3ab31521cbbcdbdd50 | bapata/PYTHON | /kaprekarno.py | 938 | 3.671875 | 4 | #!/usr/bin/python
import sys
## Kaprekar's number 6174
def high_to_low(n):
n_as_str=str(n)
slist = sorted(n_as_str)
slist.reverse()
sdigit_str = ''.join(slist)
return int(sdigit_str)
def low_to_high(n):
n_as_str=str(n)
slist = sorted(n_as_str)
sdigit_str = ''.join(slist)
return int(sdigit_str)
#... |
f6ccddf53374d0d077cb97ba80d6312692a2c56b | Emma-ZSS/repo-zhong253 | /repo-zhong253/homeworks/HW2/HW2_A.py | 597 | 4.03125 | 4 | #CSCI1133,Lab Section 004,HW2 Shanshan Zhong,Problem2A
import math
# Define the poiseuille function
def poiseuille(L,r,n):
return((8*n*L)/((math.pi)*(r**4)))
# Define the main function
def main(L,r,n):
if (L > 0) and (r >0) and (n > 0):
print('The resistance is: ', poiseuille(L,r,n))
else:
... |
e40039d7e7f579d7760b4c87ee012d4419e4b1d7 | jennyChing/onlineJudge | /10696.py | 367 | 3.53125 | 4 | def f91(N,memo):
if N in memo:
return memo[N]
if N <= 100:
memo[N] = f91(f91((N+11),memo),memo)
elif N >= 101:
ans = N - 10
memo[N] = ans
return memo[N]
if __name__ == '__main__':
memo = {}
while True:
try:
value = int(input())
if value == 0:
break
N = f91(value,memo)
print("f91(",value,... |
89ba2990eb1dd2cf3821cb5915130c0cb488dcee | navneethkour/LeetCode-Python-1 | /Number/PowerOfThree.py | 405 | 3.875 | 4 | import math
class Solution(object):
def isPowerOfThree1(self, n):
return math.log10(n) // math.log10(3) % 1 == 0
def isPowerOfThree2(self, n):
"""
:type n: int
:rtype: bool
"""
if n < 1: return False
if n == 1: return True
while n > 1:
... |
ffab7845fe7f06d3cb03205e49dc2c4e0b829cc6 | neitan626/prova_algoritmos2 | /Furadeira.py | 1,292 | 3.71875 | 4 | from Ferramenta import Ferramenta
class Furadeira(Ferramenta):
def __init__(self,nome,tensao,preco,potencia):
self._nome = nome
self._tensao = tensao
self._preco = preco
self._potencia = potencia
@property
def nome(self):
return self._nome
@nome.setter
... |
06c293fa107acca8cd5d7a2efda5dd256b4582d8 | schraderSimon/FYS-STK | /project1/code/testfunksjoner.py | 2,287 | 3.75 | 4 | import numpy as np
from small_function_library import *
tol=1e-12
def test_matrix_creation():
"""Test whether the Design Matrix is set up properly"""
testmatrix=np.zeros((3,6))
x=np.array([0,1,2])
y=np.array([1,2,3])
testmatrix[:,0]=1;
testmatrix[:,1]=y;
testmatrix[:,2]=x;
testmatrix[:,3... |
f0043c939697a60d8ae9de9dd259b0087d65f48e | kene111/DS-ALGOS | /Hackerrank and Leetcode/Kadane's algorithm.py | 1,404 | 3.953125 | 4 | """
def max_subarray(numbers):
best_sum = 0
current_sum = 0
for x in numbers:
current_sum = max(0, current_sum + x)
best_sum = max(best_sum, current_sum)
return best_sum
"""
'''
def max_subarray(numbers):
best_sum = 0
best_start = 0
best_end = 0
current_sum = 0
... |
08316a51bcb2bca6ead20fc240a9437c74159be2 | lcsdn/RL-alphazero | /RLcode/data_structures/tree.py | 1,111 | 4 | 4 | class DictTreeNode:
"""
Define a tree data structure, whose children are encoded in a dictionary
and whose value at each node is also encoded in a dictionary.
Instantiate a tree by its root node.
"""
def __init__(self, dict_value, parent=None, children=None):
self._dict = dict_value
... |
85e181019e9c92aeb22acc165c8a8ea725f61d58 | jaford/thissrocks | /Python_Class/py3intro3day/EXAMPLES/sequence_operators.py | 650 | 3.90625 | 4 | #!/usr/bin/env python
colors = ["red", "blue", "green", "yellow", "brown", "black"]
months = (
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
)
print("yellow in colors: ", ("yellow" in colors)) # <1>
print("pink in colors: ", ("pink" in colors))
print("colors: ", ",".jo... |
27d9ab2b5a11c523ded85d12138ea1b58705326f | CodeNovice2017/Python-Studying | /链表,单双链表,循环链表.py | 2,512 | 3.765625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author:CodeMonster
@file: 链表,单双链表,循环链表.py
@time: 2017/10/13 10:26
"""
class LNode:
def __init__(self,elem,next_=None):
self.elem = elem
self.next = next_
# list1 = LNode(1)
# q = list1
# for i in range(2,11):
# q.next = LNode(i)
# q = q.next... |
8a35979e7887c2ee166a60c145e3300a4b1f7cbd | imagine5am/project-euler | /p006.py | 141 | 3.53125 | 4 | square_of_sum = sum(range(101)) ** 2
sum_of_square = 0
for i in range(101):
sum_of_square += i ** 2
print(square_of_sum - sum_of_square)
|
5073516df87a481f1cc2e0d9167361f6423023fd | whencespence/python | /unit-3/dictionary.py | 1,036 | 4.3125 | 4 | # Dictionary and key/value pairs
student = {'name': 'Christina', 'age': '10', 'city': 'Toronto'}
# Access elements in dictionary using dictionary name followed by key
print(student['name'], student['age'], student['city'])
# Dictionary cannot have duplicate keys
car = {} # creates empty dictionary
car['make'] = 'Toy... |
c05c8cb0164d17a5561254bf64cf8da926420af9 | Seo-GwangHyeon/Code-Test-for-Job | /studied/1st Assingment/Other/crane.py | 617 | 3.5625 | 4 |
def solution(board, moves):
depth =len(board)
arr=[]
answer=0
for move in moves:
for i in range(depth):
if board[i][move-1]>0:
arr.append(board[i][move-1]);
board[i][move - 1]=0
if len(arr)>=2 :
if arr[len(arr)-2... |
9233b3922e6af26df8553e9dd2be5fa728b6fd4c | daddyawesome/CodingP | /OOP/ooprobot.py | 271 | 3.75 | 4 | class Robot:
def introduce_self(self):
print("My name is "+ self.name) # This in Java
r1 =Robot()
r1.name = "Tom"
r1.color = "Red"
r1.weight = 30
r2=Robot()
r2.name = "Jerry"
r2.color = "Blue"
r2.weight = 40
r1.introduce_self()
r2.introduce_self()
|
da234f9de093d6347a3781c1bd3843680471a2f3 | kanishkd4/Python_Learning_code | /Datacamp - Intro to python/Python Lists.py | 3,030 | 4.5 | 4 | # area variables (in square meters)
hall = 11.25
kit = 18.0
liv = 20.0
bed = 10.75
bath = 9.50
# Create list areas
areas = [hall, kit, liv, bed, bath]
# Print areas
print(areas)
# Adapt list areas
areas = ["hallway", hall, "kitchen", kit, "living room", liv, "bedroom", bed, "bathroom", bath]
# Print... |
049125c00f7225fced51ef74321ce4e77ff3c03c | nervig/Starting_Out_With_Python | /Chapter_10_programming_tasks/algorithmic_simulator_2.py | 819 | 3.859375 | 4 | class Book:
def __init__(self, title, name_of_author, name_of_make):
self.__title = title
self.__name_of_author = name_of_author
self.__name_of_make = name_of_make
def set_title(self, title):
self.__title = title
def set_name_of_author(self, name_of_author):
self.__... |
64210fd61ac05184c4f48f7777bc16052742c4a3 | Dosache/RepositorioPython006 | /ciclosfor1.py | 616 | 3.78125 | 4 | import os
par=0
impar=0
cont = 0
for x in range(10):
print("")
print("Ingrese el digito numero",cont)
num = int(input())
if num%2==0:
print("")
print("El numero es par")
par = par+1
cont = cont+1
else:
print("")
print("Es impar")
impar = impar+... |
2c60e84b81b8efad867d28bdde4bfc2f9288fdde | asperaa/programming_problems | /dp/house_robber_1d_dp.py | 347 | 3.515625 | 4 | """House Robber. 1D DP. Time - O(n). Space - O(n)"""
def max_loot(nums):
length = len(nums)
dp = [None] * (length + 1)
dp[0] = 0
dp[1] = nums[0]
for i in range(2, length + 1):
dp[i] = max(nums[i-1]+ dp[i-2], dp[i-1])
return dp[length]
if __name__ == "__main__":
arr = [1, 2, 3, 1... |
a6ac912f19232bfd806d5205e312386daac11202 | linuxheels/linuxheels | /udemy_learning/random_int.py | 324 | 4.15625 | 4 | import random
#This will create a random whole number
#random_integer = random.randint(1, 10)
#print(random_integer)
#random.random() -> Returns the next random floating point number between [0.0 to 1.0)
#This will create a random float, which is a *.* type of number
random_float = random.random() * 5
print(random_fl... |
ce7de0a325b38ed36556404a56e200d8b0b03cc4 | Bsmurfy/DNAalignment | /SequenceAlignment.py | 7,495 | 3.5625 | 4 | '''
Brendan Murphy
A program to globally align multiple DNA sequences from a FASTA file.
'''
def main():
match = 5
mismatch = -4
gap = -11
# read the FASTA file
fastafull = readfasta('MidCS4.fasta')
numofseq = min(4, len(fastafull)) # allows up to four DNA sequences, for now
... |
66fbc42e8c1a4c7fa23ef884b19d7eea75730c2b | g0dgamerz/workshop | /assignment1/dt18.py | 145 | 4.28125 | 4 | # Write a Python program to get the largest number from a list
list1 = [1, 2, 3]
list1.sort()
print("largest numer from the list is", list1[-1])
|
ebd4226cd29156923175d6b1ef12bf61017d2274 | bayeslabs/AiGym | /NLP/assignment2/utils/general_utils.py | 2,281 | 3.59375 | 4 | import sys
import time
import numpy as np
def get_minibatches(data, minibatch_size, shuffle=True):
"""
Iterates through the provided data one minibatch at at time. You can use this function to
iterate through data in minibatches as follows:
for inputs_minibatch in get_minibatches(inputs, minibatc... |
df0b15a8b8107b254a12bd8e0bfc03a8bc527e67 | preetisethi24/Python_work | /matrixReshape.py | 464 | 3.625 | 4 | from numpy import reshape as np
def matrixReshape(nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
len_of_orig_mat=len(nums)*len(nums[0])
len_of_output_mat=r*c
if len_of_orig_mat!=len_of_output_mat:
return nums
else:
... |
590d1b16b74c5ffa7fda50609e6911043628c502 | daecazu/pensamiento_computacional | /busqueda_binaria.py | 368 | 3.765625 | 4 | objetivo = int(input('Escoge un número: '))
epsilon = 0.01
bajo= 0.0
alto = max(1.0, objetivo)
respuesta = (alto + bajo) / 2
while abs(respuesta**2 - objetivo) >= epsilon:
if respuesta**2 < objetivo:
bajo = respuesta
else:
alto = respuesta
respuesta = (alto + bajo) / 2
print(f'L... |
01e39ba7dc547ee9ce53b1efe47ba1b0512ddc71 | ROB-Seismology/layeredbasemap | /data_types/circle.py | 1,631 | 3.515625 | 4 | """
Circle data
"""
from __future__ import absolute_import, division, print_function, unicode_literals
from .point import MultiPointData
__all__ = ['CircleData', 'GreatCircleData']
class CircleData(MultiPointData):
"""
radii: in km
"""
def __init__(self, lons, lats, radii, values=[], labels=... |
e0dda16699e452b381e0576515c03894f30b1145 | subhakani/python | /even or odd.py | 104 | 4.25 | 4 | n = int(input('Enter any number: '))
if n% 2 == 0:
print(n, "is EVEN")
else:
print(n, "is ODD")
|
045251e8ec5cc12655d91b579723973d8f4d1a57 | MitsosPng/PythonProjects | /PrimeNumbers.py | 793 | 3.953125 | 4 | import math
def f(x, y):
a = math.floor(math.log10(y))
return int(x*10**(1+a)+y)
def string_to_number():
string=input('Give me a string: ')
list=[]
count=0
number=0
for i in string:
count+=1
list.append(ord(i))
for i in range(count):
number=f(number... |
88c43d189566d9a61a67a4ae0fe5c37fe1e3a74f | dhairyachandra/CSEE5590-Python-Deep-Learning-Programming | /ICP1/Source Code/replace.py | 362 | 4.4375 | 4 | # Write a program that accepts a sentence and replace each occurrence of ‘python’ with ‘pythons’ without using regex
str = "I love playing with Python"
spt = str.split()
result = list()
final = ""
print (spt)
for i in spt:
if i == "Python":
i = "Pythons"
result.append(i)
for x in result:
final +=... |
c0d713923c6679608b97a7047abb41ac83075348 | cdunne10361551/10361551_DBS_CA_5 | /ConnorDunne_CA5_partB_Test.py | 6,642 | 3.671875 | 4 | #Name: Connor Dunne
#Student Number: 10361551
#Calculator Function Testing
#This programme tests the Calculator module to ensure expected values are returned
import numpy
from ConnorDunne_CA5_partB import Calculator #import Calculator module from file
import unittest #import unit test to run self assertion te... |
1e5c5a10333522f3ceebcb790cc2b63194d725a1 | fwang1395/LeetCode | /python/String/ReverseString.py | 1,791 | 4.28125 | 4 | #!/usr/bin/python
# _*_ coding: UTF-8 _*_
#Reverse String
#Write a function that takes a string as input and returns the string reversed.
# Example:
# Given s = "hello", return "olleh".
class Solution(object):
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
ret ... |
e79fca89480ebcd80a66577aa6e349bbc0f51791 | i1196689/GitPython | /test.py | 377 | 3.671875 | 4 | n = 3
i_list = []
j_list = []
k_list = []
i = 0
while i < n :
i_list.append(i)
i = i + 1
j = 0
while j < i :
j = j + 1
j_list.append(j)
k = 0
while k < j :
k = k + 1
k_list.append(k)
print('i:%s'%len(i_list))
print(i_list)
print('j:%s'%len(j_lis... |
a0191a69a952d3752fa18cac43b3810ac21548b7 | r1409/unis_linguagens_de_programacao | /1 - Idade.py | 347 | 3.703125 | 4 | dia = int(input("Digite os dias vividos: "))
idade_anos = ano2 - ano
if mes >= mes2:
if mes == mes2:
if data > data2:
idade_anos - 1
else:
idade_anos - 1
dias_passados = (30 - data) + ((12 - mes)*30) + ((mes2 - 1)*30) + data2 + (idade_anos)*365
print("Você viveu... |
82bad5f4b540ab0c905950a5a5a59d8b92331d55 | indrekots/py-challanges | /dict_to_string/test_dictToString.py | 526 | 3.515625 | 4 | import unittest
from dictToString import dictToString
class TestDictToString(unittest.TestCase):
def test_simple_dictionary(self):
self.assertEqual(dictToString({'test1':1}), 'test1=1;')
def test_with_none_value(self):
self.assertEqual(dictToString({'test1':1, 'test2':None}), 'test1=1;')
... |
b061c5058d011301c9f4101a2173f0959f58e61b | chavhanpunamchand/PythonPractice | /List_Data_Structure/reverse_string.py | 186 | 3.65625 | 4 | def convert(s):
new=""
for x in s:
new+=x
#print()
return new
s="Punamchand is scientiest"
l=s.split()
d=l[::-1]
print(d)
print(" ".join(convert(d))) |
5fafd6d4d89fb4ba602e32a166a25c95f8406ef3 | remir88/leetcode_cn | /~2.两数相加.py | 884 | 3.59375 | 4 | #
# @lc app=leetcode.cn id=2 lang=python3
#
# [2] 两数相加
#
# @lc code=start
# Definition for singly-linked list.
#class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoLists(self, l1: ListNode, l2: ListNode, l: ListNode) -> bool:
p = False
... |
c06b397a66b4d12154159606e7f5592139ab473e | alferesx/Python-Exercises | /EstruturaRepetição/Exercicio-20.py | 278 | 3.9375 | 4 | fatorial = -1
while fatorial != 16:
fatorial = int(input('Digite o valor da fatorial: '))
if fatorial == 16:
break
total = 1
while fatorial != 1:
total = total * fatorial
fatorial = fatorial - 1
print( 'Fatorial: ',total)
|
7b09b097e1b69a00df496464bc655d75dd72f0d0 | Gambrinus/Rosalind | /Python/SSET.py | 1,801 | 4.3125 | 4 | #!/usr/bin/env python
""" Rosalind project - Problem: Enumerating Subsets
Problem
A set is the mathematical term for a loose collection of objects, called elements.
Examples of sets include {the moon, the sun, Wilford Brimley} and R, the set
containing all real numbers. We even have the empty set, repr... |
aa517d0b7cbd0d16c7407c6587e55b523bc1c7c8 | AkshaySadhu/ShopLocally-Internship | /objpython.py | 428 | 3.734375 | 4 | class myclass:
def __init__(self, name, age, phno):
self.myName = name
self.myAge = age
self.phoneNum = phno
@property
def name(self):
return self.myName
@name.setter
def name(self, name):
self.myName = name
obj = myclass("Akshay",20,9036)
print(... |
2ce3abb5a331ee6a8d77033711b0d71c169da74e | JohnCrissman/topic-model-creator | /testing_simple.py | 819 | 3.515625 | 4 | # testing simple functions
# '''
# classifications = ['good', 'bad']
# n = 5
# list_of_classifications = [item for item in classifications for i in range(n)]
# print(list_of_classifications)
# '''
# classifications = ['bad', 'good']
# n = 999
# list_of_classifications = [item for item in classifications for i in range... |
1d3ce3214ebfb9f3eafe37bf4ebc81f1656577d6 | anabeatrizzz/exercicios-pa-python | /exercicios_4/exercicios_4_02.py | 636 | 3.9375 | 4 | """
Escreva um programa que leia o nome e o preço de 10 produtos.
Logo após realizar o cadastro dos produtos, pedir para o usuário digitar um valor,
no qual deverá ser realizada uma pesquisa e exibir apenas os produtos que possuem preço até o valor digitado pelo usuário.
"""
nomes = []
precos = []
for c in range(0, 1... |
bb65c8bb0d3b0bfb9a3cd4c8783e64dacba7506e | Barret-ma/leetcode | /32. Longest Valid Parentheses.py | 1,420 | 3.828125 | 4 | # Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
# Example 1:
# Input: "(()"
# Output: 2
# Explanation: The longest valid parentheses substring is "()"
# Example 2:
# Input: ")()())"
# Output: 4
# Explanation: The longest valid par... |
dc72351469ecce193c0d0aec8c7dea75d765f22f | Kateryna252/Start_dragon | /Module_3_min_2_min/duplicate.py | 309 | 3.875 | 4 | import random
n = int(input("please write lenght of list\n"))
list1 = []
for i in range(n):
list1.append(random.randint(0,n))
# print(set(list1))
list1_without_dublicates = []
for i in list1:
if i not in list1_without_dublicates:
list1_without_dublicates.append(i)
print(list1_without_dublicates)
|
6455792ed822e1c284fd96602ca66c3fe02e0b32 | or12k/Hangman_python_code | /hangman_unit/hangman_unit_8.py | 1,296 | 3.984375 | 4 | def print_hangman(num_of_tries):
"""
VARIABLE- HANGMAN_PHOTOS (dict)- from unit 1
the FUNCTION PRINT:
one of the 7 photos in HANGMAN_PHOTOS-
with the help of a VARIABLE-num_of_tries that represent
how many times the user
guessed the wrong letter, and HANGMAN_PHOTOS
dict[key] = value
... |
eb8b21718c1882cc7a94701812fc81c6996c6eab | Sabakalsoom/Learning-Python | /Arithmetic_Order_of_Precedence.py | 517 | 4.1875 | 4 | """
multiplication and division have the same order of precedence so it does not matter which one we do before
and has a higher precedence over + and -
"""
print(2+4*3/2)
"""
we use parenthesis when we want our own order of precedences.
"""
print((2+4)*3/2)
print((2+4*2)*3/2) #Multiplication has a ... |
5267aecc0af112e2974a527cbd78855bfb6b9273 | kdockman96/CS0008-f2016 | /ch4-ex/ch4-ex12.py | 1,079 | 4.25 | 4 | # Ask the user for the starting number of organisms
organisms = int(input('Enter the starting number of organisms: '))
# As the user the average daily population increase as a percentage
daily_pop_increase = float(input('Enter the average daily population increase as a decimal: '))
if daily_pop_increase < 0 or daily_... |
b7a0b6138844a869b49d60d58b0bab414b2a1851 | TheSleepingAssassin/CodeFolder | /py/Morse/functions.py | 664 | 3.78125 | 4 | from dictionary import *
def encrypt(message):
cipher = ''
for letter in message:
if letter != ' ':
cipher += code[letter] + ' '
else:
cipher += ' '
return cipher
def decrypt(message):
message += ' '
decipher = ''
citext = ''
for letter in message... |
c9da3d82628308138d3fcc42e52d0d45c6d5405c | bfark13/PythonExercises | /IntroProjects/CodeStruct.py | 1,010 | 3.6875 | 4 | def print_artist(album):
print(album['Artist_Name'])
def change_list(list_from_user):
list_from_user[2] = 5
def print_name(album):
print(album["Album_Title"])
def make_album(name, title, numSongs=10):
album = {'Artist_Name': name, 'Album_Title': title}
if numSongs:
album["Song_Count"] = n... |
691df28180fb0c0888484e8f0cde9c06f745bd4a | indy728/python_course | /Python_Type_DataStructure_Basics/lists.py | 439 | 4.15625 | 4 | # lists are indexed and can be sliced and can hold any variety of data types
my_list = [1, 2, 3]
print(len(my_list))
print(my_list[1:])
next_list = [4, 5, 6]
double_list = my_list + next_list
print(my_list + next_list)
print(double_list)
# lists are mutable
double_list[4] = "turd sandwich"
print(double_list)
double_lis... |
681ff8795111dff6c05e64e70d5aa9e30c10acbe | Elie-Kh/COMP472---AI | /Game.py | 5,592 | 3.609375 | 4 | from minmaxAI import summon_ai_overlord
from win_check import win_check
from Board import board_game,x_dict,column_letters,move_check
# Variables below are used in the function
# p_play variables are for getting user input
play_x = 0
play_y = 0
p_play_x = 0
p_play_y = 0
play_x_old = 0
play_y_old = 0
p1_turn = True
p1... |
c88efde09bc8d821fd427557d4e8f4071797f972 | Assa-goDori/python | /pythonex/0811/comprehensionex1.py | 910 | 3.90625 | 4 | '''
Created on 2020. 8. 11.
@author: GDJ24
comprehensionex1.py : 컴프리핸션 예제
패턴이 있는 list, dictionary, set을 간편하게 작성할 수 있는 기능
'''
numbers = []
for n in range(1, 11) :
numbers.append(n)
print(numbers)
#컴프리핸션 표현
print([x for x in range(1, 11)])
clist = [x for x in range(1, 11)]
print(clist)
... |
12e7a2c3e52b27789b0047f31588d2b3e4ad9385 | YanqingWu/Sci-kit-Learning | /数据降维.py | 1,035 | 3.671875 | 4 | #PCA(主成分分析)
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets,decomposition,manifold
%matplotlib
def load_data():
iris = datasets.load_iris()
return iris.data,iris.target,iris.target_names
def test_PCA(*data):
X,y = data
pca = decomposition.PCA()
pca.fit(X)
print(... |
604eeed856456477b79ea7bd69fb294e33403082 | Danilo-Xaxa/python_curso_em_video | /Opa meu rei 2.py | 152 | 3.6875 | 4 | a = ('Opa meu rei')
print(a.split())
print(' '.join(a))
print(a.replace('Opa', 'Eae'))
#Inclusive, aqui dá pra eu escrever qualquer coisa que eu quiser |
f6892abad6f52c63535cfc3cd3f4082b291fb832 | KyleLopin/Potentiostat_GUI | /tkinter_canvas_graph.py | 1,766 | 3.546875 | 4 | __author__ = 'Kyle Vitautas Lopin'
import Tkinter as tk
class canvas_graph_embed(tk.Frame):
def __init__(self, master, properties):
tk.Frame.__init__(self, master=master)
self.graph = tk.Canvas(master=self, width=_properties['width'], height=_properties['height'])
self.graph.pack(expand=... |
ad302f4e9411abedc0dda5b135677abae9f50a0c | caianne/mc102 | /exercicios/Aula 5/Slide_19.py | 993 | 4.09375 | 4 | #Slide 19 da Aula 05
print('Programa para calcular o valor da comissão, dada o valor da transação.')
transação=float(input('Informe o valor da transação: R$ '))
if (transação<=2500.00):
comissão=30+0.017*transação
if (comissão>39.00):
print('O valor da comissão é: R$ %.2f' %comissão)
else:
... |
cc9c93c60566f684091fa183ed49ea52fa12d3e6 | rwgeaston/alias-method-discrete-finite-probability | /next_num.py | 2,894 | 3.671875 | 4 | # https://en.wikipedia.org/wiki/Alias_method
import random
from math import floor
from numbers import Real
class InvalidInputs(Exception):
pass
class RandomGen:
_distribution = None
def __init__(self, distribution, random_source=None):
if not distribution:
raise Inval... |
ed737dddd5f705fbc5100b423b40a9dd64e92ec2 | Audarya07/Daily-Flash-Codes | /Week3/Day2/Solutions/Python/prog4.py | 110 | 3.734375 | 4 | val = 1
for i in range(1,5):
for j in range(i):
print(val**3,end=" ")
val+=1
print()
|
22b850eb44f441f73d0381235b02dda06a234608 | aleksey-masl/hello_world | /functions.py | 1,611 | 3.8125 | 4 | def say(message, times = 1):
print(message * times)
say('Привет')
say('Мир', 5)
print('#########################################################')
# Ключевые аргументы
def func(a, b=5, c=10):
print('a равно', a, ', b равно', b, ', а c равно', c)
func(3, 7)
func(25, c=24)
func(c=50, a=100)
func(a='обязательно ... |
9dd9e7244f8bc089c4f81cb759649724a807b0fe | nagask/CrackingTheCodingInterview | /StacksAndQueues/Stack.py | 425 | 3.703125 | 4 | class Stack():
def __init__(self):
self.array=[]
self.t=-1
def pop(self):
a=self.array.pop(self.t)
self.t=self.t-1
return a
def push(self,x):
self.array.append(x)
self.t=self.t+1
def peek(self):
return self.array[self.t]
... |
250693ad6bea3efc8e537cdbf1fbdadbd0d1bce4 | sksumanta/python3Basic | /listComprehension.py | 926 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 24 10:31:48 2018
@author: Sumanta
"""
# The range function in the loop
for i in range(5):
print(i)
##################### List Comprenhension ############################
lis=[]
for x in range(7):
lis.append(2**x)
print(lis) # -------- ... |
75f73f0dcad89a01808ff44176bac3987c8b784c | van7b/PythonCompiler | /compiler/examples/lexer_syntax/c5.py | 107 | 3.71875 | 4 | def findmax(x,y):
if x > y:
a=[1,2,3,4]
if y > x:
b=[1]
l=[0,1,"hello","world"]
print findmax(2,4)+6
|
d47b083cda7924f7101f3fad0dafc862a7645483 | domarcone/Exercicios-Python | /ex4.py | 367 | 3.875 | 4 | #Faça um Programa que peça as 4 notas bimestrais e mostre a média.
def main():
m1 = int(input("insira a primeira nota \n "))
m2 = int(input("insira a segunda nota \n"))
m3 = int(input("insira a terceira nota \n"))
m4 = int(input("insira a quarta nota \n"))
total = ((m1 + m2 + m3 + m4) / 4)
... |
642295cb9f0efdea183ec26c1d6d004f32238c44 | comojin1994/Algorithm_Study | /Sungjin/Math/1247.py | 340 | 3.5625 | 4 | import sys
input = sys.stdin.readline
def check(N):
if N == 0: return "0"
elif N < 0: return "-"
elif N > 0: return "+"
else: return "Error"
if __name__ == '__main__':
for _ in range(3):
N = int(input())
total = 0
for _ in range(N):
total += int(input())
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.