blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
0df1205879a3f2d9f6c47bd06b7b0ddb51501d5f | imzhen/Leetcode-Exercise | /src/38.count-and-say.py | 1,147 | 3.65625 | 4 | #
# [38] Count and Say
#
# https://leetcode.com/problems/count-and-say
#
# Easy (32.87%)
# Total Accepted: 128749
# Total Submissions: 383122
# Testcase Example: '1'
#
# The count-and-say sequence is the sequence of integers beginning as follows:
# 1, 11, 21, 1211, 111221, ...
#
#
#
# 1 is read off as "one 1" or 11... |
92543b9a46acf12d37f5ac4b442efc96521a0a42 | letifer/course | /PythonWeek2/ExPyth2-3.py | 390 | 3.734375 | 4 | def fibo(n):
print("Начинаю вычислять " + str(n) +"й член последовательности Фибоначчи")
if n == 0: result = 0
elif n == 1: result = 1
else: result = fibo(n-1) + fibo(n-2)
print("Вычислил " + str(n) + "й член последовательности Фибоначчи-" + str(result))
return result
fibo(15)
|
40f02e26cb8bdc362c74716b06939e9d50a681ff | jincurry/standard_Library_Learn | /dataStructures/collections/nametuple/collections_nametuple_person.py | 253 | 4.03125 | 4 | import collections
Person = collections.namedtuple('Person','name, age, sex')
Bob = Person(name='Bob', age=20, sex='male')
John = Person(name='John', age=21, sex='female')
for person in [Bob, John]:
print('{} is a {} year old {}'.format(*person))
|
9c4dc5fcbd49400770ec505cba6a9289cb87e388 | thefront/coding-practice | /python_samples/4assign/lab4.1.py | 617 | 3.734375 | 4 | #!/usr/local/bin/python3
# NAME: Richard Tzeng
# FILE: lab4.1.py
# DATE: <21014-07-20 Mon>
# DESC: This script returns the size of the circle and whether the two circles
# collide.
from shape import Shape
from circle import Circle
c1 = Circle(0, 0, 20)
c2 = Circle(0, 0, 20)
c1_xdelta = 2
c1_ydelta = 3
c2_xdelta = 1
... |
b7c7ee1005b19d19417a8fa6ff29ba737b3d2a63 | GoldF15h/KMTIL | /DATA_STRUCTURE_PROBLEM/7/lab7_4.py | 2,889 | 3.984375 | 4 | class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def __str__(self):
return str(self.data)
class BST:
def __init__(self):
self.root = None
def insert(self, data):
if self.root == None :
self.root ... |
3cf431bcc22cda1081856f56711c25482a16c66e | pengyuhou/git_test1 | /leetcode/990. 等式方程的可满足性.py | 786 | 3.65625 | 4 | class Solution(object):
def equationsPossible(self, equations):
def find(x):
if x == p[x]:
return p[x]
else:
p[x] = find(p[x])
return p[x]
p = [i for i in range(26)]
for i in equations:
if i[1] == '=':
... |
03f6b186c0858c30b3ec64a7954bc98d6c2b169f | StephenTanksley/cs-algorithms | /moving_zeroes/moving_zeroes.py | 1,662 | 4.1875 | 4 | '''
Input: a List of integers
Returns: a List of integers
'''
"""
U - Input is a list of integers. The list of integers will have some 0s included in it.
The 0s need to be pushed to the tail end of the list. The rest of the list needs to remain in order.
P1 (in-place swap plan) -
1) We need a way of... |
2736df577418fcb24cb2046aa47827a41baf32a8 | lance2088/py-run | /VirtualMachine.py | 5,283 | 3.75 | 4 | '''
Python Virtual Machine
description: run instructions on a stack-based machine
'''
import time
class Interpreter:
def __init__(self):
#value stack
self.stack=[]
self.pstack=-1
#run-time stack
self.frame_stack=[]
self.pfstack=-1
self.pframe=-1
#registers
self.PC=0
self.TEMP=No... |
70f03e3c56c6ee95965162b841da5b8ce3387895 | yashsharma15/tathastu_week_of_code | /day1/program2.py | 72 | 3.59375 | 4 | import math
a = int(input("Enter number :"))
b = math.sqrt(a)
print (b)
|
867282bf7e4c3b2133987d05a648967e5a324f01 | danielhamc/PythonInformationInfrastructure2 | /1.28_Two_Vowels_v3.py | 341 | 4.1875 | 4 |
file_name = input("Please enter a file name: ")
word_line = line.strip() for line in open(file_name, "r")
word_v = [word for word in [word for sentence in word_line for word \
in sentencese.split()]
print("All lines in the file: ", word_line)
print("The words in the file that contain 2 or more vo... |
c4d8a21d8290c3296e2423fa9835032f1a6292b3 | jeremysong/2048game | /main/game.py | 1,527 | 3.96875 | 4 | from main.board import Board, Direction
__author__ = 'jeremy'
class Game:
def __init__(self):
"""
Constructor. Create new game board.
"""
self.__board = Board()
self.__movement = {
Direction.up: self.__board.move_up,
Direction.down: self.__board.mov... |
c542bd1796c845bb44f911194f475593d760c9d3 | bdugersuren/algorithmic-problems | /Others/medium/MinMaxStackConstruction.py | 1,155 | 3.671875 | 4 | # Feel free to add new properties and methods to the class.
class MinMaxStack:
def __init__(self):
self.stack = []
self.min = None
self.max = None
def peek(self):
if self.stack:
return self.stack[-1][0]
def pop(self):
if self.stack:
num = se... |
331272f50e3ef6708ddb7e09ffd9893bae626908 | lcmartin35/estudo | /Desafio025.py | 288 | 3.96875 | 4 | print(' === Desafio 025 ===\n')
print('Procurando String')
print("""
Crie um programa que leia o nome de uma pessoa e diga
se ela tem "SILVA" no nome.
\n""")
nome = str(input('Digite oseu nome completo: ')).strip()
print('Seu nome tem Silva? {}'.format('SILVA' in nome.upper()))
|
02856cf1ea4e10578f96db50f0c8874935a1c2d2 | RonnyCaicedoV/2DO-PARCIAL-EJER.-EN-CLASE | /busque3.py | 1,889 | 3.609375 | 4 | class Busqueda:
def __init__(self,listas=None):
self.__lista= listas
@property
def lista(self):
if self.__lista != None:
return self.__lista
else:
print("Lista esta vacia")
def busquedaLineal(self,buscado):
lon = len(self,... |
21e845e74cdf89b75c82be612d542ee2e2749736 | vipulkumarpandya/Python-Session4-Assignment1 | /filterLongWords-Problem1.2.py | 242 | 3.578125 | 4 | def filter_long_words(lst=[],n=0):
longwrd=[wrd for wrd in lst if len(wrd) > n ]
return longwrd
a = input("Enter a sentense : ").split(" ")
b = input("Enter lenght of word : ")
print(filter_long_words(a,int(b)))
|
706fce14c4d778b87f75a20cbba024657f131883 | YelikeWL/credit-card-validation | /credit-card-number-validation.py | 2,469 | 4.25 | 4 | ''' Credit card number validation
Credit card numbers follow certain patterns: It must have between 13 and 16 digits,
and the number must start with:
■ 4 for Visa cards
■ 5 for MasterCard credit cards
■ 37 for American Express cards
■ 6 for Discover cards
In 1954, Hans Luhn of IBM proposed an algorithm for validatin... |
0b5896845154d22468a26b0756e877f2c569a309 | itggot-stefan-chan/adventure_game | /adventure/adventure.py | 878 | 3.71875 | 4 | import world
import player
def init():
#world.wipe_places()
world.generatePlace()
print('Welcome to an adventure game!')
print('Type "move(left or right)" to move to an another place, "look" to look at the place you are in')
print ('Type "pick up" to see if you can pick up an object and "inventory"... |
31233594837ca69b32bfee045f046ad79dbe805d | sruthipg/Python_tutorial | /single_inheritance.py | 213 | 3.796875 | 4 | class A(object):
def start(self):
print("In A")
class B(A):
def start(self):
print("In B")
ob=B()
ob.start()
# Inherit the parent class method from child class if the same method exist
|
e4b5af82fdaba153619c5baf8d3b65be05bfe0d1 | Darrenrodricks/PythonProgrammingExercises | /GitProjects/reverseStr.py | 156 | 4.25 | 4 | # Please write a program which accepts a string from console and print it in reverse order.
a = str(input("Please enter something: "))
b = a[::-1]
print(b)
|
147b92d27c8a293ef906782d5a133a3670a1f002 | DeanHe/Practice | /LeetCodePython/TwoSumIV-InputIsaBST.py | 1,021 | 3.84375 | 4 | """
Given the root of a Binary Search Tree and a target number k, return true if there exist two elements in the BST such that their sum is equal to the given target.
Example 1:
Input: root = [5,3,6,2,4,null,7], k = 9
Output: true
Example 2:
Input: root = [5,3,6,2,4,null,7], k = 28
Output: false
Constraints:
The nu... |
5ea1ce3b5ea6f9beb4c013d12b362ee17f01a757 | ivanwakeup/algorithms | /algorithms/dynamic_programming/max_square.py | 771 | 3.625 | 4 | def maximalSquare( matrix):
if not matrix:
return 0
max_square = 0
rowL = len(matrix)
colL = len(matrix[0])
dp = [[0 for _ in range(colL)] for _ in range(rowL)]
for i in range(colL):
dp[0][i] = int(matrix[0][i])
max_square = max(max_square, dp[0][i])
for i in range... |
cd037b74a005f003c07f339325e136ffb62e9dcc | mjmcandrew/Coursera_2020 | /Bioinformatics1_Spring2020/Func_FrequentWordsWithMismatchesAndReverseComplements.py | 6,315 | 3.734375 | 4 | def FrequentWordsWithMismatchesAndReverseComplements(text, k, d):
words = []
#Initializes the empty list 'words' which will store frequent patterns
#accounting for mismatches, as well as the reverse complement of the input
#string text.
freq = ComputingFrequenciesWithMismatches(text, k, d)
#Comp... |
07eb668482a05b0a03c5f9614d18a7ff5a179776 | MasterKali06/Hackerrank | /Problems/easy/Implementation/counting_Valleys.py | 387 | 4.03125 | 4 | '''
https://www.hackerrank.com/challenges/counting-valleys/problem
'''
exam1 = ['U','D','D','D','U','U','U','D','D','U']
def countingValley(steps,path):
sealevel = 0
vallycount = 0
d = {'U':1 , 'D':-1}
for step in path:
sealevel += d[step]
if sealevel == 0 and step == 'U':
... |
58653112a0da5fcb9c5c36199e21af08175f6c68 | allainclair/disc-estrutura-dados | /aula10/pessoa_quadrado.py | 1,255 | 3.640625 | 4 | import math
def main():
# l = []
altura, peso, nome, idade = 160, 60, 'Maria', 31
pessoa1 = Pessoa(altura, peso, nome, idade)
pessoa1.print()
print()
pessoa2 = Pessoa(150, 50, 'Jao', 30)
pessoa2.print()
print()
quadrado1 = Quadrado(1)
quadrado1.print()
print()
qua... |
608553cb93011d88a6bb9f2bbaa8155e52656bc9 | CastleYeager/Alien-Invasion-by-Castle | /bullet.py | 1,509 | 4.1875 | 4 | """
通过子弹类来管理子弹的所有功能和动作
"""
import pygame
# 子弹需要依靠精灵类来继承
from pygame.sprite import Sprite
class Bullet(Sprite): # 之所以要继承自精灵类,是因为精灵类可以通过精灵编组类来管理一系列精灵对象
"""
管理子弹的动作和方法
"""
# 初始化子弹,即生成子弹,需要在飞船的顶部中间位置初始化出一枚子弹
def __init__(self, screen, ship, settings):
super().__init__()
... |
efbd76c63121db0209084d398c705cc4e7010ccc | gloryfromca/ExpertPythonProgramming | /chapter12_Optimization_SomePowerfulTechniques/memoize.py | 538 | 3.921875 | 4 | from functools import lru_cache
import time
def fibonacci_o(n):
if n < 2:
return 1
else:
return fibonacci_o(n - 1) + fibonacci_o(n - 2)
begin = time.time()
for i in range(10000):
fibonacci_o(15)
end = time.time()
print("time of origin func:", end-begin)
@lru_cache(1280, True)
def fibonacc... |
05eb11aecdffe52c3b293e8c5a0b38b76c2007f6 | hcvazquez/python-string-manipulation | /examples/swap_case.py | 262 | 3.96875 | 4 | def swap_case(s):
name_list = []
for i in s:
if i.isupper():
name_list.append(i.lower())
elif i.islower():
name_list.append(i.upper())
else:
name_list.append(i)
return ''.join(name_list)
|
f73984f6f357996feab97fdb103bd0e8f168aadb | BiggyG-Alex/Mapper | /Krypto.py | 1,489 | 4.03125 | 4 | # transposition cipher
# encryption function
def scramble2Encrypt(plainText):
# stripSpaces(plainText)
evenChars = ""
oddChars = ""
charCount = 0
for ch in plainText:
if charCount % 2 == 0:
evenChars = evenChars + ch
else:
oddChars = oddChars + ch
c... |
a11600ce1cb9f90d59e76cbb97c61c0bf0b524d8 | durandal42/projects | /chores/chores.py | 2,374 | 3.90625 | 4 | import itertools
import collections
import random
NUM_ROOMMATES = 5
'''
In a chore assignment a, a[i] is the roommate assigned to chore[i].
assumption: equally many chores as roommates
assumption: each roommate assigned at most one chore
Therefore, a chore assignment is a permutation of roommate indexes.
'''
def is_... |
8013a55370ba7ab7abae8ab13aa425032aad80b7 | china-jiajia/python-test | /laonanhai/while-count.py | 96 | 3.859375 | 4 |
count = 0
while count < 10:
print(count)
count = count + 1
else:
print('else')
print('end') |
ba966913bf31e97838a102a03a7fe1434787158c | paalso/mipt_python_course | /8_testing/2/A/test_find_two_equal.py | 463 | 3.53125 | 4 | import unittest
from A import find_two_equal
class FindTwoEqual(unittest.TestCase):
def test_find_two_equal(self):
self.assertEqual(find_two_equal([8, 3, 5, 4, 5, 1]), 5)
self.assertEqual(find_two_equal([5, 5, 1, 4, 2, 3]), 5)
self.assertEqual(find_two_equal([1, 4, 2, 3, 5, 5]), ... |
2679c16a0a8878d414833bb759de230781976727 | anondev123/F20-1015 | /Lectures/24/cat-dog/train-model.py | 9,893 | 3.515625 | 4 | # From: https://www.tensorflow.org/tutorials/images/classification
# mport packages
# ----------------------
# start by importing the required packages. The os package is used to read files
# and directory structure, NumPy is used to convert python list to numpy array and
# to perform required matrix operations and ma... |
2411ac03cffa867412e2228d53017a0cbabf8ea1 | zbck/N_reines | /ParcoursEnLargeur.py | 1,531 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 4 14:30:54 2016
@author: emacedegastines
"""
from Fonctions import Fonctions
class ParcoursEnLargeur(Fonctions):
def parcoursEnLargeurRec( listeSolution, i, n ):
''' fonction récursive pour le parcours en largeur
- listeSolution : list... |
f27589dbf1af2401abf9bb52ec04450ea9ec4d24 | Derrickragui/fff | /prac.py | 111 | 3.71875 | 4 | age = 23
name = "Derrick kuria"
txt="my name is {0} and I am {1}{price:.2f}"
print(txt.format(name,age,price = 34))
|
bf0a89ec36de255bd4965ad306aedb4cc04867fc | DoctorLai/ACM | /leetcode/2022. Convert 1D Array Into 2D Array/2022.py | 549 | 3.796875 | 4 | # https://helloacm.com/teaching-kids-programming-convert-1-d-array-to-2d-matrix-reshape-algorithm/
# https://leetcode.com/problems/convert-1d-array-into-2d-array/
# EASY, ARRAY
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
if len(original) != m * n:
... |
63057a89c09c8614e9e05fa6377eb6165a3e7071 | jalex3421/Python-Basicos | /IntroReview4.py | 1,212 | 4.3125 | 4 | '''
Autor: Alejandro Meza
Fecha: 01-06-2020
Little introduction of Python part 4
'''
#FUNCTION BASICS
def max (x,y):
if(x >y):
return x
else:
return y
x = (int)(input("Introduce x: "))
y = (int)(input("Introduce y: "))
print(f"The maxVal is {max(x,y)}")
#also we can... |
fa484edc56f7628628b18299a7f36de03329d4f4 | GabrielCernei/codewars | /kyu5/Pete_The_Baker.py | 911 | 3.984375 | 4 | # https://www.codewars.com/kata/pete-the-baker/train/python
'''
Write a function cakes(), which takes the recipe (object) and the available ingredients
(also an object) and returns the maximum number of cakes Pete can bake (integer). For simplicity
there are no units for the amounts (e.g. 1 lb of flour or 200 g of s... |
769b4647968dd3eeddbee1dbf4163d952f22c56d | dxfang/algo-problems-python | /climbing_stairs.py | 660 | 3.78125 | 4 | class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n < 3:
return n
'''
Base Conditions
'''
two_steps_below = 1
one_step_below = 2
current_step = 0
... |
5a5fe824d8458b2249db821b4611d0e6e7bf66a2 | joaabjb/ifpi-ads-algoritmos2020 | /fabio03_while/f3_q19_soma_sequencia3.py | 267 | 3.703125 | 4 | def main():
N = int(input('Digite o valor de n: '))
n = N
s = 0
c = 1
while c <= N:
if c % 2 != 0:
s += c / n
else:
s -= n / c
c += 1
n -= 1
print(f'A soma dos termos é {s:.3f}')
main() |
0169ca21146c3d688a13bdce929b769fd7611309 | sihota/CS50W | /ORM_API/classes3.py | 2,046 | 4.03125 | 4 | class Flight:
#declare counter static or class variable
counter = 1
def __init__(self,origin,destination,duration):
#keep track of id number
self.id = Flight.counter
Flight.counter += 1
#keep track of passengers
self.passengers = []
#details about flight
... |
b840820ae202bc6cf08ff45eced6a7e87b110fa8 | jacquerie/leetcode | /leetcode/0867_transpose_matrix.py | 366 | 3.6875 | 4 | # -*- coding: utf-8 -*-
class Solution:
def transpose(self, A):
return [[A[j][i] for j in range(len(A))] for i in range(len(A[0]))]
if __name__ == "__main__":
solution = Solution()
assert [[1, 4, 7], [2, 5, 8], [3, 6, 9],] == solution.transpose(
[
[1, 2, 3],
[4, ... |
e47fdef577939f41f78481a30efbbf9bd1e01c2c | PGaliato/Python | /Exercicio_6.py | 889 | 3.796875 | 4 | tentativas = 5
jogador = input('Jogador: ')
print ('Ola, tente adivinhar o numero correto')
print ('Você tem 5 tentativas')
print ('Gerando um número de 0 á 10...\nGood Luck')
numero = (7)
while(tentativas > 0):
chute = int(input('Chute: '))
tentativas -= 1
if tentativas >= 0:
... |
4419389c8b82cb5b5f1e93d5721e99e61684ac4a | balajisomasale/Data-Analyst-Career-Path | /Data Analyst career path/Step 1 Python programming/Intermediate_Python for Data science/python files/Challenge_ Modules, Classes, Error Handling, and List Comprehensions-186.py | 1,201 | 3.765625 | 4 | ## 2. Introduction to the Data ##
import csv
f=open('nfl_suspensions_data.csv','r')
nfl_suspensions=list(csv.reader(f))
nfl_suspensions=nfl_suspensions[1:]
years={}
for each in nfl_suspensions:
row_year=each[5]
if row_year in years:
years[row_year]=years[row_year]+1
else:
years[row_year]=1
... |
d9f3fe2f9903dbc9fe9fcbbd314afba476ff0dd5 | m0hanram/ACADEMICS | /clg/sem4/PYTHONLAB/psbasics_2/ps2basic_14.py | 412 | 3.8125 | 4 | def function(lst):
length = len(lst)
for x in range(length):
i = x+1
while i < length:
if lst[x] == lst[i]:
del lst[i]
length -= 1
i -= 1
i += 1
a = []
m = int(input("enter the number of elements : "))
for y in range(m):
... |
4acfe1f96f3d904ddfa91cf8bcaaf5727f0e5c38 | wufans/EverydayAlgorithms | /2018/67. Add Binary.py | 850 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 27 09:47:18 2018
@author: wufan
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Out... |
f8458b4c862a3f1a963b795456e15eff41c8880f | fsym-fs/Python_AID | /month05/teacher/day01/demo05_reshape.py | 318 | 3.9375 | 4 | """
demo05_reshape.py 变维
"""
import numpy as np
# 视图变维 reshape() ravel()
a = np.arange(1, 19)
print(a, a.shape)
b = a.reshape(2, 3, 3)
print(b, b.shape)
b[0,0,0] = 999
print(a, a.shape)
print(b.ravel())
# 复制变维 flatten()
print(b.flatten())
# resize()
b.resize(2, 9)
print(b)
|
7587d88c578e5e7fbe6c896bff1ce248634aa31b | GatitoLunar/Ejercicios-de-python | /Ejercicio 10.py | 143 | 3.828125 | 4 | def procedimiento(numeros):
simbolo = "*"
for value in numeros:
print(simbolo * value)
procedimiento([1,2,3,4,9,8,7,4,5,6,7,3,2,1,0]) |
060f95a78ad7888770d33339879903fcb7d13cc1 | yth98/InfoDep | /20210305_sql/print_db.py | 623 | 3.75 | 4 | import sqlite3
import pandas as pd
from tabulate import tabulate
DB_NAME = "example.db"
db = sqlite3.connect(DB_NAME)
cursor = db.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = cursor.fetchall()
for table_name in tables:
table_name = table_name[0]
if table_name.startswi... |
5ef87ca03230efc14858caaef6039449f556594d | lama-imp/python_basics_coursera | /Week2_tasks/33_number_length.py | 84 | 3.78125 | 4 | now = int(input())
n = 0
while now != 0:
n += 1
now = int(input())
print(n)
|
25357a914e05ad2b3b26b1d6a42d871ecb667a29 | avishekjaiswal/Python_assessment | /ques13.py | 283 | 4.28125 | 4 | def col_sequence(x):
num_seq = [x]
if x < 1:
return []
while x > 1:
if x % 2 == 0:
x = x / 2
else:
x = 3 * x + 1
# Added line
num_seq.append(x)
return num_seq
n = input("enter your number")
print(col_sequence(n))
|
5c2c14d6f64801c7574244cc918eef0589a7e0a3 | anthonyzhub/Pong | /ball.py | 1,931 | 3.796875 | 4 | import pygame
from random import randint
BLACK = (0,0,0)
class Ball(pygame.sprite.Sprite):
def __init__(self, color, width, height):
# Initialize parent (Sprite) class
super().__init__()
# Define ball's characteristics
self.image = pygame.Surface([width, height])
self.im... |
0065fc2e93897e63f378c804ef6da049a3c2b053 | kailunfan/lcode | /219.存在重复元素-ii.py | 1,569 | 3.59375 | 4 | #
# @lc app=leetcode.cn id=219 lang=python
#
# [219] 存在重复元素 II
#
# https://leetcode-cn.com/problems/contains-duplicate-ii/description/
#
# algorithms
# Easy (38.29%)
# Likes: 178
# Dislikes: 0
# Total Accepted: 49K
# Total Submissions: 124.9K
# Testcase Example: '[1,2,3,1]\n3'
#
# 给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索... |
3ea45a8bda0e5ea7fb98451f5942af697c8bdb18 | 19PalaceWinston/WinstonPalace-Python | /Unit7ALab/Unit7ALab.py | 1,004 | 3.671875 | 4 |
def main():
myPet1 = pet("Dog","Gracie","Great Dane")
print(myPet1.pName)
print(myPet1.petType)
myPet1.whatIsIt()
myPet2 = pet("Cat","River","Ragdoll")
print(myPet2.pName)
print(myPet2.petType)
myPet2.whatIsIt()
myCage1 = cage("snake","True")
print(myCage1.cType)
print(myCag... |
01dc43c005c3f708348e2782b0cab924cdfe938e | aws108/Introduction_to_python | /02- ejercicios/Sesión 4/ej06.py | 632 | 3.9375 | 4 | # -*- coding: utf-8 -*-
class Animal:
"""Clase base para mostrar la herencia"""
def __init__(self, nombre, patas):
self.nombre = nombre
self.patas = patas
def saluda(self):
print "El animal llamado "+str(self.nombre) + " saluda"
class Amigo:
def __init__(self, nombre):
self.nombre = nombre
def sal... |
6aaccf2a7676c41245a7a15ebd787e02c70e2ca2 | dragon0/py-sysadmin-talk | /modules/hypot.py | 421 | 4.03125 | 4 | def hypotenuse(x, y):
"""Computes the distance from the origin to the point (x, y)
:param x: the point's x-coordinate
:param y: the point's y-coordinate
:return: number. the distance from (0, 0) to the point (x, y)
>>> hypotenuse(3, 4)
5.0
>>> hypotenuse(5, 12)
13.0
"""
return ... |
b8756c891b0688e4998ab481ad0215ea2d54c4a1 | AIDemyanov/Python_hw_3 | /3_task_3.py | 391 | 4.25 | 4 | # Реализовать функцию my_func(), которая принимает три позиционных аргумента, и возвращает сумму наибольших
# двух аргументов
def my_func(a, b, c):
if a >= b and b <= c:
print(a + c)
elif a <= b and a >= c:
print(a + b)
else:
print(b + c)
my_func(1, 2, 3) |
1205192649b5257701c6054122361f6dd9acc75f | wutaosamuel/myTest | /python/obj/initfalse.py | 399 | 3.5625 | 4 | from ..object import Obj
def printFalseinit():
#obj = Obj()
#print("false init obj: ", obj)
#obj = Obj("name", 1)
#print("print out object: ", obj)
# def __init__(self, name="", id=-1):
# if name == "" or id == -1:
# return False
#self.Name = name
#self.ID = id
print("Cannot pri... |
563524c7f8296d29b3f1c02d66a0fb14ea654a34 | duplessisaa/Time_Series_Forecating_JBrownlee | /6_Univariate_multi_step_vector_output_MLP.py | 1,354 | 3.609375 | 4 | '''
We will look at a vector output that represents multiple time steps of one variable, for example:
In = [10 20 30] out = [40 50]
In = [20 30 40] out = [50 60]
In = [30 40 50] out = [60 70]
'''
import tensorflow as tf
import numpy as np
def Split_sequence(seq, n_steps_in, n_steps_out):
X, y = list(), list()
... |
28405529e749ef829b229e56c83461af0ab8b496 | gsudarshan1990/codilitypython | /Inheritance_3.py | 308 | 3.625 | 4 | class Animal:
sound=""
def __init__(self,name):
self.name = name
def speak(self):
print("{} and {}".format(self.name,self.sound))
class Piglet(Animal):
sound="dnajfnas"
class Cow(Animal):
sound="Minkx"
piglet=Piglet("hello")
cow=Cow("nedls")
piglet.speak()
cow.speak() |
58bdf9919d8844ba141bcd3be08c92243fda34e3 | afend/projecteuler | /evenfibnums.py | 761 | 3.75 | 4 | #!/usr/bin/python
def main():
'''
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four mill... |
8ff4ebbad2c303b5e7b477392eb51781000a44a8 | Mdmetelus/Intro-Python-I | /src/cal.py | 2,011 | 4.71875 | 5 | """
The Python standard library's 'calendar' module allows you to
render a calendar to your terminal.
https://docs.python.org/3.6/library/calendar.html
Write a program that accepts user input of the form
`calendar.py month [year]`
and does the following:
- If the user doesn't specify any input, your program should... |
5d75e765117b1e8731d5998daecb4c69551f5c6d | brohum10/python_code | /daniel_liang/chapter02/2.21.py | 371 | 3.8125 | 4 | savings = eval(input("Enter the monthly saving amount: "))
formula = (1 + 0.00417)
month_1 = savings*formula
month_2 = (savings+month_1)*formula
month_3 = (savings+month_2)*formula
month_4 = (savings+month_3)*formula
month_5 = (savings+month_4)*formula
month_6 = (savings+month_5)*formula
print("After the ... |
623d4a78baa66e9716be3e73832c2d9cce3f7028 | AkitoShiga/python | /beginningPython/file/file.py | 549 | 3.953125 | 4 |
# これでファイルオブジェクトが生成される、デフォルトは読み込みモード 'r'
#f = open('./hoi.txt')
f = open('somefile.txt', 'w')
# 自動で改行される訳ではない
print(f.write('Hello, \n')) #出力されるのは文字数
print(f.write('World!, \n'))
print(f.write('Konichiwa\n'))
print(f.write('皆さん!\n'))
f.close()
f = open('somefile.txt', 'r')
print(f.read(4))#引数に数値を渡すとその文字数読み込み
#途中から出力さ... |
e8ba00668955f4391eee9bd37e6c44993e6aefac | OtherU/Python_Cursos_online | /desafio_053.py | 869 | 3.953125 | 4 | # ------ Modules ------ #
# ------ Header & Footers ------ #
header = str(' Desafio 053 ')
subfooter = ('-' * 68)
footer = ('=' * 68)
# ------ Header ------ #
print('{:=^68}'.format(header))
# ------ Body ------ #
phrase = input('Digite uma frase: ').strip().upper()
sptphrase = phrase.split()
jnphrase = ''.join(sptph... |
7b74aa8b6a60c13a57fea48bc2bbc84f9e75bbfb | Pyabecedarian/Machine-Learning-Assignment | /ml_ex6/visualizeBoundaryLinear.py | 937 | 3.625 | 4 | import matplotlib.pyplot as plt
import numpy as np
from ml_ex6.plotData import plotData
def visualizeBoundaryLinear(X, y, clf):
"""
VISUALIZEBOUNDARYLINEAR plots a linear decision boundary learned by the
SVM
VISUALIZEBOUNDARYLINEAR(X, y, model) plots a linear decision boundary
learned by the SVM ... |
1d651f1ae20fb53cebeb8d112902536125e740ad | mvousden/pytest-lets-explore | /1/binary_converter.py | 559 | 4.1875 | 4 | def convert_integer_to_binary_string(inputInteger, zeroPadLength=0):
"""
Converts an integer to a zero-padded binary string.
"""
return "{{:0{}b}}".format(zeroPadLength).format(inputInteger)
def test_my_converter():
assert convert_integer_to_binary_string(0, 3) == "000"
assert convert_integer_... |
b40dc509aaac5eef155580d3c800f1046c669a6c | cookiemon5ter/yahtzee | /yahtzee.py | 13,625 | 3.53125 | 4 | import random
import yaht
import os
import sys
class Player:
def __init__(self):
self.upper = ["ones", "twos", "threes", "fours", "fives", "sixes"]
self.lower = ["fh", "tk", "fk", "ss", "ls", "yahtzee", "chance"]
self.scores = {}
for key in self.upper + self.lower:
... |
999e14dc5d221fc868df64401d5237ccce444ecf | NathanielNat/python-peregrination | /names.py | 345 | 3.84375 | 4 | from name_func import get_formatted_name
print("Enter 'q' to quit")
while True:
first = input('Enter your first name: ')
if first == 'q':
break
last = input('Enter your Last Name: ')
if last == 'q':
break
formatted_name = get_formatted_name(first,last)
print(f'Well formatted n... |
7c1eb924262193e27bc0fa6e46e5b738c90a9ef1 | Nick7421/PythonJourney | /GreaterThan.py | 241 | 4.28125 | 4 | #This is my First Attempt at Code!!!
import time
y = 15
x = int(input("Enter a number: "))
print ('Is your number greater than Y?')
time.sleep(3)
if x > y:
print('X is Greater')
else:
print('Y is Greater Try Again!')
|
4bb6cdb8bb8ddf9ba1804131fa84bf24a41d0b73 | zhiweiguo/my_leetcode | /offer/50.py | 1,253 | 3.625 | 4 | '''
第一个只出现一次的字符
在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。
示例:
s = "abaccdeff"
返回 "b"
'''
class Solution:
def firstUniqChar(self, s: str) -> str:
'''
两步走,第一步遍历统计各个字符出现的次数
第二步则找到首个次数为1的字符
'''
l = len(s)
if l == 0:
return ' '
if l == 1:
retu... |
816856db49037e5513cee617bc0108ed0338b17d | cevatarmutlu/data-transfer-between-databases | /src/db/DBFormatEnum.py | 194 | 3.546875 | 4 | # In-Python module
from enum import Enum
class DBFormatEnum(Enum):
"""
Represents the type of obtained data from databases.
"""
TUPLE = "tuple"
DICT = "dict" |
638baae1c2a2c75c673a40dcaf166ffce1025c98 | lsr-explore/udacity-movie-trailer | /src/media.py | 1,234 | 4.15625 | 4 | """
Movie class
"""
class Movie(object):
"""
Definition for a movie card
"""
title = ""
poster_image_url = ""
trailer_youtube_url = ""
rating = ""
genre = ""
storyline = ""
year = ""
def __init__(self, title, thumbnail, trailer):
"""
Constructor
... |
d31372ff8d58289554c430ab977e248b59818e60 | mmarianaa/Python-exercises | /ex14.py | 803 | 3.671875 | 4 | # Exercício 14
# João, comprou um microcomputador para controlar o rendimento diário de
# seu trabalho. Toda vez que ele traz um peso de peixes maior que o
# estabelecido pelo regulamento de pesca do estado de São Paulo (50 quilos)
# deve pagar uma multa de R$ 4,00 por quilo excedente. João precisa que você
# faç... |
7b5f0fbf104dc6f408b3aa3b4eb3e2adf5eefc45 | vincenttuan/Python0709 | /d11/ATM.py | 1,394 | 4.03125 | 4 | class Account:
__money = 0 # (私有)物件屬性/變數/資產
def __init__(self, x) -> None: # 建構式
self.__money = x # 開戶時所存的第一筆金額
def transfer(self, accountName, x):
print("轉帳給" + accountName + " 金額: $" + str(x))
if x <= 0:
print('轉帳金額必須 > 0')
return
if x > self.__... |
d810202a7323a5669c3ee20dbb2425a98ac66eee | gkbrk/RosalindSolutions | /revc/revc.py | 553 | 4.09375 | 4 | import sys
def complement(dna_string):
complemented_string = ""
for nucleotide in dna_string:
if nucleotide == "A":
complemented_string += "T"
elif nucleotide == "T":
complemented_string += "A"
elif nucleotide == "G":
complemented_string += "C"
... |
e87871696d7fc479401e0b229531fc84ffbc3091 | WENTAO6688/Data-Structure-and-Algorithm- | /LInkedlist_1_Reverse linkedlist 翻转链表.py | 416 | 3.9375 | 4 | '''
Reverse a linked list.
Input: 1->2->3->null
Output: 3->2->1->null
Input: 1->2->3->4->null
Output: 4->3->2->1->null
'''
class Solution:
def reverse(self, head):
if not head or not head.next:
return head
prev = None
cur = head
while cur:
next = cur.next... |
33fe80a06ad3a81e02a2266aa495fbc1c4f477d1 | ardeo82091/DigitalClockusing-Python | /Num.py | 1,664 | 3.578125 | 4 | from tkinter import *
import time
root=Tk()
root.title('DIGITAL CLOCK')
root.geometry('1350x700+0+0')
root.config(bg='black')
def clock():
h = str(time.strftime("%H"))
m = str(time.strftime("%M"))
s = str(time.strftime("%S"))
if int(h)>12 and int(m)>0:
lbl_noon.config(text='... |
bcb38ee8e4a738ce2b0480d652b5b402f2e5d67d | amirtip/laitecpython | /Tam2/tam5.py | 108 | 4 | 4 | x=int(input("Enter The Num:"))
print("* "*x)
for i in range(x):
print("* "," "*x," *")
print("* "*x)
|
5f9233599fd1e9ec11c3da5e3fd6f7cb1ec2abd6 | Jose-manuelR-I/R.P.1._Jose_Manuel_Ramirez | /itesco programas/Ejercicio_3_1.py | 1,483 | 4.125 | 4 | # A,B,C
A = int(input('¿Cuantas ventas tiene el producto A? '))
B = int(input('¿Cuantas ventas tiene el producto B? '))
C = int(input('¿Cuantas ventas tiene el producto C? '))
#Mayor
if A > B and A > C:
print('a) Las ventas del producto A son las más elevadas')
if B > A and B > C:
print('a) Las ventas... |
31dbb2366d098657ff57d9aa556f12d546d739f6 | Ankit8989/Sample_Data | /data.py | 340 | 4 | 4 | #Write a program to accept two numbers and print If both numbers positive If one is positive and other negative If both are negative
num_1=input("Please enter the 1st number")
num_2=input("Please enter the 2nd number")
name='Sachin'
count=0
for i in range(1,20):
print(i)
count=count+1
... |
e2e46d376a3e533d9bb7bd4f02e205d7b5b54779 | dhaarmaa/python | /menu/menuFabo.py | 1,451 | 3.59375 | 4 | import os
option = 1
userOne = None
userTwo = None
userThree= None
passwordOne = None
passwordTwo = None
passwordThree = None
while option!= 3:
try:
os.system('cls')
print("**********************************************************")
print(" * MENU * ... |
de6ea6fb149007f8e84af42ee71c10077a622ce0 | oenomel87/euler | /prob02.py | 259 | 3.53125 | 4 | '''
피보나치 수열에서 400만 이하의 수 중 짝수의 총합
'''
result = 0
prev = 1
cursor = 1
while cursor + prev < 4000000:
tmp = cursor
cursor += prev
prev = tmp
if cursor % 2 == 0:
result += cursor
print(result)
|
864751af283b91b6670c677044477de052014a67 | lomnpi/data-structures-and-algorithms-python | /Sorting/insertion_sort.py | 264 | 4.03125 | 4 | def insertionSort(iterable):
for j in range(1, len(iterable)):
key = iterable[j]
i = j - 1
while i >= 0 and iterable[i] > key:
iterable[i+1] = iterable[i]
i -= 1
iterable[i + 1] = key
return iterable
|
7aa91879ff952c7782b5ff418709f2a086cee86b | deepanshululla/DataStructuresAndAlgo | /python/sorting/sortAnalysis.py | 3,466 | 3.796875 | 4 | from timeit import default_timer
import time
def bubbleSort(list1):
alist=list1
for passNum in range(len(alist)-1,0,-1):
for i in range(0,passNum):
if alist[i]>alist[i+1]:
temp=alist[i]
alist[i]=alist[i+1]
alist[i+1]=temp
#print "after %d pass"%(len(alist)-passNum)
#print(alist)
return alist;
... |
f830d41faa6f7a6e3d9187213a8c2166ad84347f | JackBid/context-aware-recommender | /inputOutput.py | 2,382 | 3.546875 | 4 | import pandas as pd
class IO:
def __init__(self, recommender):
super().__init__()
self.recommender = recommender
# Get a user ID and confirm it exists in our dataset
def getUserID(self):
print('Enter user ID:')
userID = input()
if userID not in list(self.recommend... |
4f01a182f67f79424bd0ad287a0fa4d4a06a6092 | SHPStudio/LearnPython | /function/functionProgram.py | 2,865 | 3.578125 | 4 | # 函数式编程
# 函数式编程是一种抽象度高的编程方式
# 推崇一种没有副作用的函数形式,也就是说只要输入确定,输出就确定。
# 但是有很多语言都是有变量的,所以一个函数的输出还受到其他变量的影响,所以这种函数就是有副作用的。
# 现在比较提倡函数式编程因为输入输出的确定代表要进行单元测试等等就会非常的简单容易,程序定位错误也简单。
# 高阶函数 即参数可以是函数 返回值也可以是函数
# 那参数是函数怎么写 其实就是函数的名字 函数的名字其实就相当于指向具体函数的指针
# b = abs
# print(b(-10))
# 如果我们改变abs的引用
# abs = 10
# print(abs(10))
# 那么他就会报错了
# ... |
79c56d6213b41773282fb77eb46e4cdec654333e | Kirill0684/Python_GitHUB | /1/task_5.py | 418 | 4.21875 | 4 | revenue = int(input('revenue: '))
costs = int(input('costs: '))
if revenue < costs:
print('the company is unprofitable.')
elif revenue == costs:
print('zero profit company.')
else:
profitability = (revenue - costs) / revenue
print('the company is profitable. Profitability: ', profitability)
size = i... |
606e8cdc53a38d30a5cfc9b8571738d870c2c6be | kin7274/Dugeundugeun-Python | /5장/연습문제8.py | 666 | 3.953125 | 4 | import turtle
t=turtle.Turtle()
x1=int(input("큰 원의 중심x1 : "))
y1=int(input("큰 원의 중심y1 : "))
r1=int(input("큰 원의 반지름r1 : "))
x2=int(input("작은 원의 중심x2 : "))
y2=int(input("작은 원의 중심y2 : "))
r2=int(input("작은 원의 반지금r2 : "))
distance=((x1-x2)**2 + (y1-y2)**2)**0.5
t.up()
t.goto(x1, y1-r1)
t.down()
t.circle(r1)
t.up()
t.go... |
edbce06de0d4d820076b2c63d7f1795703f619de | gleny4001/Python | /birthday-wisher/main.py | 1,203 | 3.953125 | 4 | # 4. Send the letter generated in step 3 to that person's email address.
# HINT: Gmail(smtp.gmail.com), Yahoo(smtp.mail.yahoo.com), Hotmail(smtp.live.com), Outlook(smtp-mail.outlook.com)
import smtplib
from datetime import datetime
import pandas
import random
my_email = "gleny4001@gmail.com"
password = "1234"
today ... |
f20982e8146960957ade13097f1f8479b5cb2efd | CnvH/ringqueue | /ringqueue.py | 2,120 | 4.0625 | 4 | """module ringqueue
Implements a ring queue (list wrapped into a ring).
When ring size reaches max_ring_size new additions overwrite oldest:
max_ring_size: the maximum size of the buffer -keep modest!
size: integer up to max_ring_size, current size of the queue
head_ptr: points to head of list
tail_ptr: poin... |
8d8f66d2b43e8da26e8c8ca79839ea0723e4d0c0 | JennyLoveCode/Algorithm | /self/py_leetcode/q16_insert_pos.py | 866 | 4.1875 | 4 | """
Given a sorted array and a target value, return the index if the target is found.
If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6], 5 2
[1,3,5,6], 2 1
[1,3,5,6], 7 4
[1,3,5,6], 0 0
"""
def main():
arr = [... |
d249cbdac0e93a527196322ad3f67a8055bded16 | gregoriovictorhugo/Curso-de-Python | /Mundo-01/pydesafio Mundo01/des016.py | 113 | 4.0625 | 4 | import math
n = float(input('Digite aqui um número: '))
print('O número inteiro é: {}'.format(math.floor(n)))
|
3543e4f304bca98a3653ff26034d92a751d22ee9 | jakehoare/leetcode | /python_1_to_1000/692_Top_K_Frequent_Words.py | 945 | 3.78125 | 4 | _author_ = 'jake'
_project_ = 'leetcode'
# https://leetcode.com/problems/top-k-frequent-words/
# Given a non-empty list of words, return the k most frequent elements.
# Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the
# word with the lower alphabetical or... |
4dbf91e5162078992173386a993b2ba3b197a8fb | HelleEngstrom/solid | /liskov/main.py | 541 | 3.71875 | 4 | from rectangle import Rectangle
from square import Square
def run():
rec = Rectangle(2, 4)
squ = Square(5)
print("Area of rectangle: " + str(rec.calculateArea()))
print("Area of square: " + str(squ.calculateArea()))
rec.changeHeight(5)
print("Area of rectangle: " + str(rec.calculateArea()))
... |
01707ee349b234e62e5cdd8a04c57bf6da07f627 | thaus03/Exercicios-Python | /Aula13/Desafio54.py | 527 | 3.921875 | 4 | # Crie um programa que leia o ano de nascimento de sete pessoas.
# No final mostre quantas pessoas ainda não atingiram a maioridade e quantas já são maiores.
from datetime import datetime
maiores = 0
menores = 0
anoAtual = datetime.now().year
for i in range(0, 7):
anoNasc = int(input('Digite o ano de nascimento: ... |
3832645b997f8d52235c792ad7567224292cd6f6 | mihirkelkar/EPI | /List_And_Arrays/Count_Min_Steps_To_Desired_Array/countMinSteps.py | 720 | 3.859375 | 4 | def countMinSteps(target_array):
result = 0
zero_count = 0
while zero_count < len(target_array):
zero_count = 0
target_array, temp = action(target_array)
print target_array, zero_count
print "-----------------------"
result += temp
for ii in target_array:
if ii == 0:
zero... |
413b798fdce4ad0e4ff18656b3a762313f1afa89 | pythonkurs/pjohansson | /scripts/getting_data.py | 517 | 3.5 | 4 | """Downloads escalator service data of the NYC subway system and calculates the
fraction of those having the status of 'Repair'."""
from pjohansson.session2 import download_data, get_outage_data, count_repair
raw_data = download_data()
outage_data = get_outage_data(raw_data)
num_repair = count_repair(outage_data)
pr... |
29c7184425e037671795c781d7f827b2e7924ec4 | andrefcordeiro/Aprendendo-Python | /Uri/strings/1629.py | 720 | 3.609375 | 4 | # Descompacta Face
def soma(intStr):
soma = 0
for i in range(0, len(intStr)):
soma += int(intStr[i])
return soma
while True:
n = int(input())
if n == 0:
break
for i in range(0, n): #le cada visitante
d = 0 # 1 ou 0
num = input()
cont0 = 0
con... |
323482cd3c037a9db496669257884ba3c30140d7 | Filip0/TDT4120 | /TDT4120-Python/oving7/kortstokk.py | 815 | 3.5 | 4 | from sys import stdin
from itertools import repeat
def merge(decks):
a = decks[0]
for i in range(1,len(decks)):
c = a
a = []
b = decks[i]
while c and b:
if c[0][0] < b[0][0]:
a.append(c[0])
c.pop(0)
else:
... |
d981f732cf92847aebdfcff1c5be5375c83cccfd | PhilipEskins/Python-netninja | /projects/area_calc.py | 260 | 4.03125 | 4 | #name = input('Tell me your name, punk:')
#age = input('...and your age:')
#print(name, 'you are', age)
#Calc the area of a circle
radius = input('Enter the radius of your circle (m):')
area = 3.142 * int(radius)**2
print('The area of your circle is:', area)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.