text stringlengths 37 1.41M |
|---|
l=[]
highest=[]
scores=set()
for i in range(int(input())):
name=input()
score=float(input())
l.append([name,score])
scores.add(score)
h=sorted(scores)[-1]
for name,score in l:
if h==score:
highest.append(name)
for i in sorted(highest):
print(i,end="\n") |
# Code for testing if statement in python
nm=input("Enter name ")
basic=int(input("enter basic salary "))
if basic>5000:
allowance=basic*45/100
bonus=basic*30/100
elif basic>3000:
allowance=basic*25/100
bonus=basic*10/100
else:
allowance=basic*15/100
bonus=0
total=basic+allowance+bonus
print("T... |
# Addition of elements of Lists and NumPy arrays
import numpy as np
# Working with lists
lst1=[1,2,3,4,5]
lst2=[1,2,3,4,5]
add_res=lst1+lst2
print(add_res)
#creating array from list
np_lst1=np.array(lst1)
np_lst2=np.array(lst2)
npres=np_lst1+np_lst2
print(npres)
# Content of Sohamglobal.com |
# Demo program on class and object
class numbers:
a=0
b=0
def __init__(self):
print("Welcome to python class")
def calcsum(self):
sum=self.a+self.b
return sum
def showmessage(self,name):
print("your name is ",name)
obj=numbers()
obj.showmessage("... |
#-*- coding:utf-8 -*-
nums = [10,11,12,13,14,15]
#在for中无break会执行的,没什么用
for num in nums:
print num
break
else:
print('='*10) |
import random
USER_PROMPT = "guess a number between {} and {}: \n"
LOWEST_NUMBER = 1
HIGHEST_NUMBER = 10
while True:
randomNumber = random.randint(LOWEST_NUMBER, HIGHEST_NUMBER)
userGuess = 0
while randomNumber != userGuess:
userPrompt = USER_PROMPT.format(LOWEST_NUMBER, HIGHEST_NUMBER)
... |
def repeatedStringMatch(self, A, B):
if B in A:
return 1
if set(B) > set(A):
return -1
n = len(B) // len(A)
if B in A * n:
return n
if B in A * (n + 1):
return n + 1
if B in A * (n + 2):
return n + 2
|
weight = float(input("Weight: "))
w_type = input("L(bs) or (K)g: ")
# lbs = float(weight) * 0.45
# kg = float(weight) / 0.45
if w_type.upper() == "L": #the upper method will make the data input uppercase
converted = weight * 0.45
print(f'You are {converted} kgs')
elif w_type.upper() == "K":
converted... |
list = [2, 3, 1, 5, 2, 1, 3, 9, 9]
for remove in list:
if list.count(remove) == 2:
list.remove(remove)
print(list)
#Mosh way
list = [2, 3, 1, 5, 2, 1, 3, 9, 9]
unique = []
for number in list:
if number not in unique:
unique.append(number)
print(unique)
x, y, z, a, b = unique
print(x)
|
# 퀴즈 9 클래스
class house:
def __init__(self, location, house_type, deal_type, price, completion_year):
self.location = location
self.house_type = house_type
self.deal_type = deal_type
self.price = price
self.completion_year = completion_year
def show_detail(self):
... |
import cs50
from sys import argv
if len(argv) != 2:
print ("usage error")
exit()
db = cs50.SQL("sqlite:///students.db")
rows = db.execute('SELECT * FROM students WHERE house = ? ORDER BY last, first' , argv[-1])
for row in rows:
if row["middle"] == None:
print( row["first"] + " " +... |
letter = input()
grade = float(ord('E') - ord(letter[0]))
if len(letter) == 2:
if letter[1] == "+" and grade != 4:
grade += 0.3
elif letter[1] == "-":
grade -= 0.3
# if letter is 'F', our calculation gives -1
if grade > 0:
print(grade)
else:
print(0.0) |
print("Guess a number from 1 to 10. You have 3 tries.\n")
i=1
while i<=3:
num= int(input("Guess: "))
i = i + |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 6 12:25:49 2021
@author: RileyBallachay
"""
import threading
def worker():
"""thread worker function"""
print ('Worker')
return
threads = []
for i in range(5):
t = threading.Thread(target=worker)
threads.append(t)
t.start(... |
# coding: utf-8
# In[14]:
import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import pandas_datareader.data as web
# In[15]:
#we're setting a visulization style
style.use('ggplot')
# In[16]:
#we're setting a start and end datetime object
#this will be the rang... |
# print a question about age
print("How old are you?", end= ' ')
# ask for the age
age = input()
# print a question about height
print("How tall are you?", end=' ')
# input for height
height = input()
# print a question about weigh
print("How much do you weigh?", end=' ')
# input for weight
weight = input ()
# print al... |
print(" Hi, this is a tracker for you body status. ")
x = int(input(" Number of times you have thought about your body: "))
y = int(input(" Number of times you have gone out for a run: "))
def adonis():
z = y - x
print(f"\t {z}")
print(" When this numer is positive you will feel better.")
adonis()
|
print("""You enter a dark room with two doors.
Do you go through door #1 or door #2?""")
door = input("> ")
if door == "1":
print("There is a giant bear here eating a cheese cake.")
print("What do you do?")
print("1. Take the cake.")
print("2. Scream at the bear.")
bear = input("> ")
if bear... |
#ex13: Parameters, unpacking, variables
from sys import argv
# 'import' tells the program to use 'argv' from the 'sys' module
# (sometimes also called 'libraries')
# 'argv' is the 'argument variable'. This variable holds the
# arguments you pass into your python script when you run it.
script, first, second, third =... |
#ex05: More variables and printing
name = 'Claire F. Esau'
age = 28 # not a lie
height = (5*12) + 6 # inches
weight = (9*14) + 10 # lbs
eyes = 'Hazel'
teeth = 'White'
hair = 'Brown'
print "\nLet's talk about %s." % name
print "She's %d inches tall." % height
print "She weighs %d pounds." % weight
print "Actually that... |
# -*- coding: utf-8 -*-
import platform
import os
from datetime import datetime, date
def limpiar_pantalla():
sistema_operativo = platform.system()
if sistema_operativo.lower() == "windows":
os.system("cls")
else:
os.system("clear")
def leer_entero(mensaje, min_val=None, max_val=None, requ... |
class Solution:
def repeatedNTimes(A):
for a in range(len(A)):
if A[a] in A[:a]:
return A[a]
sol = Solution
print("Container with most water = {}" .format(sol.repeatedNTimes([5,4,3,3]))) |
def diagonalDifference(arr):
# Write your code here
return arr
sum_a = 0
sum_b = 0
for i in range(len(arr)):
sum_a = sum_a + arr[i][i]
sum_b = sum_b + arr[len(arr)-i-1][i]
return abs(sum_a - sum_b)
print("a")
print(diagonalDifference([[11, 2, 4], [4, 5, 6], [10, 8, -12]])) |
def readFile(filepath):
file = open(filepath, "r")
lines = [line.strip("\n") for line in file.readlines()]
return lines
def infix2postfix(expression):
postExp = []
stack = []
for i in range(len(expression)):
if expression[i] == " ":
continue
elif '0' <= expression[i... |
pizzas = ['calabreza', 'peperonni', 'Muzzarela']
for pizza in pizzas:
print("I love pizza de " + pizza.title())
print("I really love pizza de " + pizza.title() + "\n")
friends_pizzas = pizzas[:]
friends_pizzas.append('tortella')
print(friends_pizzas)
print()
print("Minhas pizzas favoritas são: " + str(pizzas)... |
animals = ['dog', 'cat', 'bear']
for animal in animals:
print ("A " + animal.title() + " would be a great domestic animal!")
print("Which one of these animals could be a great domestical animal!") |
import sys
import inspect
import heapq, random
from collections import deque
"""
Data structures useful for implementing SearchAgents
"""
# TODO modify the priority queue function as per the latest doc strings to add all the required functionalities.
class Stack(deque):
"A container with a last-in-first-out (LIF... |
'''读取csv文件'''
import csv
data = csv.reader(open('info.csv','r'))
for user in data:
print(user)
# print(user[0]) #读取每一行的第1个数据 |
# Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.
# Example 1:
# Input: [0,1]
# Output: 2
# Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.
# Example 2:
# Input: [0,1,0]
# Output: 2
# Explanation: [0, 1] (or [1, 0]) is a longest... |
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
nested loop through rows, columns
check if coord is target,
return true if target
for quicker - use binary search
... |
class TicTacToe:
'''
A Tic-Tac-Toe board is given as a string array board.
Return True if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game.
The board is a 3 x 3 array, and consists of characters " ", "X", and "O".
The " " character represents ... |
def contains_duplicates(lst):
"""
Runtime is O(n log n). Sorting is O(n log n) and the loop is O(n)
>>> contains_duplicates([1,2,3,1])
True
>>> contains_duplicates([1,2,3,4])
False
"""
lst.sort()
for idx in range(1, len(lst)):
if lst[idx-1] == lst[idx]:
return Tr... |
s = 'azcbobobegghekl'
#s = 'abcbcd'
currentString = s[0]
longestString = ''
i = 0
for i in range(1,len(s)):
if s[i] >= s[i-1]:
currentString = currentString + s[i]
else:
if len(currentString) > len(longestString):
longestString = currentString
currentString = s[i]
print longe... |
"""Given a string s, find the longest palindromic substring in s. You may
assume that the maximum length of s is 1000.
(寻找最大长度的回文子串)
exp:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
"""
def longestPalindrome(self,s):
"""
当新增一个字符最大回文子串长只可能增加1或者2.而且最大回文子串办函这个新字符。
"""
max... |
import os, fnmatch
def getCsvFiles(path, extension=None):
"""
Listing files with given extension in a folder.
:param path: string - folder in which the files are
:param extension: string - format: "*.csv" file extension what it looks for
:return: list - list of csv files in from the path
"""... |
import streamlit as st
import pandas as pd
import plotly.express as px
#Título
st.title("Mi primer app de streamlit")
#Para ejecutar, desde la consola escribimos: streamlit run nombrearhivo.py
#header
st.header("Semestre Sep-Enero 2021")
#Texto
st.text("Herramientas para el análisis de datos")
#Markdown
st.markdow... |
a = int(input())
b = int(input())
d = 1
while d % a != 0 or d % b != 0:
d += 1
print(d)
|
#!/usr/bin/env python
import math
# Draw an arc of equally spaced circles
arcRadius = 400 # Radius of the arc to place the circles on
arcDegrees = 180 # Number of degrees to spread the circles over
arcOffset = 0 # Angle to start from
pinRadius = 7 # Radius of the circles
pinCount = 25 # How many c... |
#! python3
"""Class Employee Module."""
# Program name: jmEmployee.py
# Author: Jonathan McDonald
# Date last updated: 4/16/2017
# Purpose: This is a class constructor for the Employee class that
# that will hold the attributes: name, ID, dept, and job title.
# import modules #
# import antigravity
# none
... |
#! python3
# Program name: jmKilometers.py
# Author: Jonathan McDonald
# Date last updated: 2/26/2017
# Purpose: This program converts user entered Kilometers to Miles and displays both back to the user
# Initialize My Variables #
##myMile as Float
##MY_K_M_CONST As Float
MY_K_M_CONST = 0.6214 #conversion con... |
# Program name: jmCelsiusToFah.py
# Author: Jonathan McDonald
# Date last updated: 2/17/2017
# Purpose: This program prints a conversion table of Celsius and Fahrenheit temperatures
# from 1 through 20 degrees Celsius.
# Initialize My Variables #
##my_PL_inc As Int #this is my print line increment
my_PL_in... |
#! python3.4
#######################################################################
# Author: Jonathan McDonald
# CST 100 Fall B
# ID: 1208311061
# Section:
# Date: 11/05/2014
#######################################################################
# PROGRAM DESCRIPTION
# This program will play a number gu... |
'''
Created on 19 Feb 2018
@author: williamherbosch
Proof-of-Concept : Convolution Neural Network for MNist dataset
This program offers an alternative architectural structure to neural network design by applying a convolutional model to the MNist dataset.
A convolutional network is a form of deep, feed-forward neural... |
# python ScriptDescomposicion.py [int]
import sys
if len(sys.argv)==2:
numero=sys.argv[1]
longitud=len(numero)
unidades={1:"unidad",2:"decena",3:"centena",4:"unidad de millar",5:"decena de millar"}
numero=numero[::-1]
for i in range(longitud):
num=int(numero[i]) * 10**i # numero*(10^i)
print(f"{num:5d} {unidad... |
numbers = [14,5,6,7,4,8,15]
def square(x):
return x*x
# new_list = []
# for x in numbers:
# new_list.append(square(x))
new_list = [square(x) for x in numbers]
new_list2 = map(square, numbers)
print(new_list)
print(list(new_list2))
|
age = 23
if age >= 18:
adult = True
print("you're an adult")
else:
adult = False
print("you aren't an adult")
# ternary operator
adult = True if age >= 18 else False # one line
print("you're an adult" if adult else "you aren't an adult")
#
number = 10
print("this number is very large" if number > 1... |
numbers = [1, 5, 7, 12, 5, 10, 4, 2]
new_list = []
for number in numbers:
if number % 2 == 0:
new_list.append(number)
print(new_list)
# Using list comprehension
new_list_C = [x for x in numbers if x%2 == 0]
print(new_list_C)
#
powers_of_two = [2 ** x for x in numbers]
print(powers_of_two)
#
words = ['aU... |
n1=float(input("Ingresa el primer numero: "))
n2=float(input("Ingresa el segundo numero: "))
print("Son iguales?",n1==n2)
print("Son iguales?",n1!=n2)
##
cadena=input("Escribe una cadena")
lon=len(cadena)
print("es mayor que 3 y menor que 10?",3<lon<10)
##
NumeroMagico=12345679
NumeroUsuario=int(input("ingresa un numer... |
## script, abrir con cmd ejemplo: python sys_1.py "palabra" 5
import sys
print("hola")
if len(sys.argv)==3:
texto=sys.argv[1]
repeticiones=int(sys.argv[2])
for r in range(repeticiones):
print(texto)
else:
print("introduce los argumentos correctamente")
|
##tuplas, usa metodos muy similares a las listas pero no pueden ser modificadas
tupla=(10,[1,2,3],"hola",-50);
print(tupla,"\n",tupla[0],"\n",tupla[1],"\n",tupla[1:],) ## No se puede redefinir el valor de una tupla
print(len(tupla),len(tupla[1]))
print(tupla.index(-50)) ## dice el indice en donde se encuentra el valor ... |
def CuentaAtras(num):
num-=1
if num>0:
print(num)
CuentaAtras(num) # Funcion llamada a si misma
else:
print("fin de la cuenta")
print(f"fin de la funcion {num}") # el mensaje se muestra al final de cada ocacion
# que se llamo la funcion a si misma
CuentaAtras(5)
## Factorial
def Factorial(num... |
#finding hcf using Euclids division lemma
def HCF(NO1, NO2):
if NO2>NO1:
temp = NO1
NO1 = NO2
NO2 = temp
del temp
while True:
rem = NO1 % NO2
if rem != 0:
NO1 = NO2
NO2 = rem
else:
return NO2
break
... |
import sys
sys.path.insert(0, '..')
from search import *
if __name__ == '__main__':
print('### Test Recursion ###')
l = [4, 5, 8, 9, 10, 15, 17]
print(f'list: {l}')
key = 15
print(f'search for {key}: ', end = '')
print(binary_search(l, 0, len(l)-1, key))
key = 4
print(f'search for {key}: ', end = '')
print... |
#You are given a space separated list of numbers.
#Your task is to print a reversed NumPy array with the element type float.
#Input Format
#A single line of input containing space separated numbers.
#Output Format
#Print the reverse NumPy array with type float.
#Sample Input
# 1 2 3 4 -8 -10
#Sample Output
#[-10.... |
'''
You are given an array of integers. You should find the sum of the elements with even indexes (0th, 2nd, 4th...) then
multiply this summed number and the final element of the array together.
Don't forget that the first element has an index of 0.
For an empty array, the result will always be 0 (zero).
Input: A list ... |
'''
The labyrinth has no walls, but bushes surround the path on each side.
If a players move into a bush, they lose.
The labyrinth is presented as a matrix (a list of lists): 1 is a bush and 0 is part of the path.
The labyrinth's size is 12 x 12 and the outer cells are also bushes. Players start at cell (1,1).
The exit... |
# coding=utf-8
#DCT中的M和N参数,此处设置为8
MN = 8;
def Block(matrix, sizeX,sizeY):
little_matrix = []
#start_point是每个8*8矩阵的第一个点
for Y in range(0, sizeY / MN):
for X in range(0, sizeX / MN):
start_point = Y * sizeX * 8 + X * 8
#初始化中间矩阵
mid_matrix = []
... |
"""
Author: Adam Harris
Create a set of images containing a random number of omniglot charachters in arbitrary configurations,
alongside a CSV of image labels (the number of charachters contained in the image).
Omniglot characters downloaded from https://github.com/brendenlake/omniglot
Lake, B. M., Salakhutdinov, R.... |
"""
DEAD_CELLS = 0 [x as representation]
ALIVE_CELLS = 1 [* as representation]
RULES of LIFE:
Any live cell with 0 or 1 live neighbors becomes dead, because of underpopulation
Any live cell with 2 or 3 live neighbors stays alive, because its neighborhood is just right
Any live cell with more than 3 live ne... |
# string of numbers as input for 4 digit OTP generation
a=input()
str1=""
str2=""
# to iterate through the string
for i in a:
# to ignore number if it is even
if int(i)%2==0:
continue
#else for odd number square it
else:
b=int(i)*int(i)
str1=str1+str(b)
for i in rang... |
a=input().split(',')
str2=""
for j in a:
str1=""
l=[]
# to separate digits and numbers
for i in j:
if i.isdigit()==True:
l.append(i)
elif i.isalpha()==True:
str1=str1+i
l1=list(map(int,l))
l1.sort()
l1.reverse()
m=min(l1)
# if length of name given is present in ... |
#function definition
def most_frequent(string):
frequency = {}
test= string
for x in test:
if x in frequency:
frequency[x] +=1
else:
frequency [x] =1
#sorting and reversing the dictionary values
sort_freq = sorted(frequency.item... |
import random
import math
#rock crush scissors
#scissors cut paper
#paper covers rock
#lizard poisions spock
#spock lazers rock
#scissors decapites lizard
#paper disproves spock
#lizzard eats paper
#rock crushes lizard
#spock smashes scissors
def rpsSwitch(argument):
switcher ={
1: "Rock",
2: "P... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#UNAM-CERT
#
### Funcion que valide si es un palindromo recibe cadena y devuelve true o false
def valida_palindromo(cadena):
tam = 0
while tam < len(cadena):
if cadena[tam] != cadena[-(tam+1)]:
return False
tam+=1
return True
if valida_palindromo("anit... |
# In this section we take integer input from user..
row=int(input("enter no of rows"))
# This is for loop..
for i in range(1,row+1):
for j in range(1,i+1):
print("*", end="")
print()
for k in range(row+1,0,-1):
for l in range(k+1,1,-1):
print("*",end="")
print()
|
from collections import Counter
COLORS = {1,2,3,4}
def _find_constraint_and_filter(items, key, side):
"""Iterate over `items` to determine a constraint value and return a list
of elements from `items` that map to that constraint via `key`.
`items` : an iterable
`key` : a callable ac... |
"""A script to do point-in-polygon testing for GIS."""
from enum import Enum
_MAX = float('inf')
_MIN = -_MAX
class BoundaryException(Exception):
"""An exception raised when a point being tested sits on the
boundary of a polygon. That fact defines the point's inside/outside
status. An exc... |
import random;
formats = open('formats').read().split('\n');
types = ['names', 'nouns', 'units', 'updowns', 'persons', 'ages', 'n2ouns', 'futures', 'verbs', 'adjectives'];
for i in types:
exec(i+' = open("'+i+'").read().split(",");');
def generateHeadline():
format = random.choice(formats);
for i in types:
exe... |
from tkinter import *
import random
import itertools
import bot
class mastermind:
def __init__(self):
return
# handmatig de code invullen
def manualcode(self):
self.colourcode = []
colours = ['red', 'pink', 'yellow', 'green', 'orange','blue']
print('red,', ... |
n = input("")
# Apenas para saber o indice de n2
original_crive = range(3, n, 2)
crive = range(3, n, 2)
index = 0
remove = []
n2 = 0
n_int_sqrt = int(n**(0.5))
print original_crive
print n_int_sqrt
while crive[index] <= n_int_sqrt:
n2 = crive[index] * crive[index]
print crive[index], n2, original_crive.inde... |
#!/usr/bin/env python
# Copyright (c) 2021- The University of Notre Dame.
# This software is distributed under the GNU General Public License.
# See the file COPYING for details.
# This program is a simple example of how to use Work Queue.
# It is a toy example of diffusion of particles by Brownian motion.
# It accep... |
import random
# help http://blog.yhat.com/posts/the-beer-bandit.html
class BernoulliArm:
def __init__(self, p):
self.p = p
def draw(self):
return 0.0 if random.random() > self.p else 1
class EpsilonGreedy:
# constructor
# epsilon (float): tradeoff exploration/exploitation
def __... |
from numpy import *
print("Zadanie 1:")
a = arange(3)
b = arange(3,6,1)
print(a,b,a*b)
print("Zadanie 2:")
a = array([[7, 4, 2], [1, 1, 3], [0, 9, 6]])
b = array([[3, 1, 5, 1], [9, 8, 7, 5], [1, 3, 2, 4], [5, 7, 3, 0]])
print(a)
print(b)
print(a.min(axis=0), a.min(axis=1))
print(b.min(axis=0), b.min(axis=1))
prin... |
# https://www.hackerrank.com/challenges/insertionsort2/problem
# Tag(s): sorting
def _print(arr):
for x in arr:
print(x, end=' ')
print()
def insertionSort1(n, arr):
k = arr[n-1]
index = n - 2
while index >= 0:
if arr[index] < k:
if index + 1 < n:
arr[... |
from typing import Tuple
"""Given an integer, print the next smallest and next largest number
that have the same number of 1 bits in their binary representation.
"""
""" Approach
Prior observations:
- If we turn on a 0, we need to turn off a 1. i.e 0->1 and 1->0. To keep the
same number of 1 bits.
- I we 0->1 at bit ... |
# https://www.hackerrank.com/challenges/find-the-median/problem
# tag(s): sorting, implementation
if __name__ == "__main__":
n = int(input())
arr = list(map(int, input().split(" ")))
arr.sort()
print(arr[len(arr) // 2]) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from fractions import Fraction
ff = []
while True:
try:
line = raw_input()
if not line:
break
except EOFError:
break
ff.append(map(int, line.split()))
res = Fraction()
for f in ff:
res += Fraction(f[0], f[1])
print ... |
# https://omegaup.com/arena/problem/Dominos#problems
def pow(x, n, I, mult):
if n == 0:
return I
elif n == 1:
return x
else:
y = pow(x, n // 2, I, mult)
y = mult(y, y)
if n % 2:
y = mult(x, y)
return y
def identity_matrix(n):
"""Returns the n... |
def is_anagram(str_1, str_2):
return sorted(str_1) == sorted(str_2)
if __name__ == '__main__':
str_1 = input("Type first word: ")
str_2 = input("Type second word: ")
print(is_anagram(str_1, str_2))
|
# https://app.codesignal.com/interview-practice/task/uX5iLwhc6L5ckSyNC
# Tag(s): Arrays
def firstNotRepeatingCharacter(s):
conts = [0]*26
n = len(s)
for i in range(n):
conts[ord(s[i])-97] += 1
ans = '_'
for i in range(n):
if(conts[ord(s[i])-97] == 1):
ans = s[i]
... |
def scalarProduct(a, b):
assert len(a) == len(b)
a, b = sorted(a), sorted(b)
return sum(a[i] * b[i] for i in range(len(a)))
if __name__== '__main__':
a = [1, 3, 6, 8]
b = [7, 23, 1, 0]
print(scalarProduct(a, b))
|
# https://app.codesignal.com/interview-practice/task/oJXTWuwEZiC6FTw3A/description
# Tag(s): DP
def climbingStairs(n):
a, b = 1, 1
for i in range(2, n+1):
a, b = a + b, a
return a
if __name__ == '__main__':
n = int(input(''))
print(climbingStairs(n))
|
# https://www.hackerrank.com/challenges/cavity-map/problem
# Tag(s): Implementation
def find_cavities(grid:list) -> list:
n = len(grid)
for i in range(1, n-1):
for j in range(1, n-1):
if grid[i][j] > grid[i-1][j] and grid[i][j] > grid[i+1][j]:
if grid[i][j] > grid[i][j-1] a... |
# https://www.hackerrank.com/challenges/py-the-captains-room/problem
if __name__ == '__main__':
k = int(input())
room_numbers = list(map(int, input().split()))
n = len(room_numbers)
room_numbers = sorted(room_numbers)
left = []
right = []
flip = True
for i in range(n):
if flip... |
#!/usr/bin/env python3
# https://www.hackerrank.com/challenges/finding-the-percentage/problem
# tags: tipos de datos y estructuras de datos, diccionario
if __name__ == '__main__':
n = int(input())
estudiantes = {} # crear el diccionario
for _ in range(n):
# leemos el nombre y las calis como cadena... |
# https://www.hackerrank.com/challenges/alternating-characters/problem
# Tag(s): Greedy, strings
def alternatingCharacters(s):
flag_1 = 'A'
flag_2 = 'B'
x = 0
y = 0
n = len(s)
for i in range(n):
if s[i] == flag_1:
flag_1 = ('B' if flag_1 == 'A' else 'A')
else:
... |
# A object orientated game
import math
import random
class GameObject:
x = 0
y = 0
def distance_to_game_object(self, obj):
return math.sqrt(
pow(self.x - obj.x, 2) + \
pow(self.y - obj.y, 2)
)
class Player(GameObject):
pass
class Treasure(GameObject):
... |
n = int(input('Please enter a natural number greater than 1: '))
primes = []
for tested in range(2,n+1):
for p in primes:
if not tested % p: # exact division by p
break
else:
primes.append(tested)
print(primes) |
#!/usr/bin/python
#Author: Jay Gurnani
from sys import exit, argv
import os,re
def main (arg):
if len(arg) < 1:
print "Wrong syntax. Required format = ./comment_parser.py argument.java"
exit(0)
else:
checker(arg)
def checker (file_entered):
fileName, fileExt = os.path.splitext(fil... |
# Stack (Implementation: Partial)
# Queue (Implementation: Partial)
# BinarySearchTree (Implementation: Partial)
# AVL Tree (Implementation: Partial)
# Heaps (Implementation: Incomplete)
# Red Black Tree (Implementation: Incomplete)
# B Tree (Implementation: Incomplete)
# B+ Tree (Implementation: Incomplete)
# Graph... |
import turtle
import random
import time
screen = turtle.Screen()
screen.bgcolor("black")
screen.colormode(255)
t = turtle.Turtle()
for i in range(99999):
t.shape("classic")
x = random.randint(-200, 200)
height = random.randint(100,350)
t.left(90)
t.penup()
t.goto(x,-... |
import turtle
def draw_square(some_turtle):
for i in range(1,5):
some_turtle.forward(100)
some_turtle.right(90)
def draw_art():
window = turtle.Screen()
window.bgcolor("red")
#Create the turtle Brad - Draws a square
brad = turtle.Turtle()
brad.shape("turtle")
brad.color("bl... |
class Evento:
def __init__(self, nomeEvento, dataEvento, dataFim):
self.nomeEvento = nomeEvento
self.dataEvento = dataEvento
self.dataFim = dataFim
def __str__(self):
return "Nome do Evento: " + self.nomeEvento + "\nData do Evento:" + self.dataEvento
class Pessoa:
def __i... |
class SLNode:
def __init__(self,value):
self.value = value
self.next = None
class SList:
def __init__(self):
#node = SLNode(value)
#self.head = node
self.head = None
def addNode(self,value):
node = SLNode(value)
#runner = self.head #when Head has value
runner = self.head
runner = node
while(r... |
'''
x = [ [5,2,3], [10,8,9] ]
students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'}
]
sports_directory = {
'basketball' : ['Kobe', 'Jordan', 'James', 'Curry'],
'soccer' : ['Messi', 'Ronaldo', 'Rooney']
}
z = [ {'x': 10, 'y': 20} ]
'''
#1How ... |
class PhoneBook:
def __init__(self,line,dict):
self.line = line
self.phonedict = dict
if len(self.line.split()) == 2:
self.phonedict[self.line.split()[0]] = self.line.split()[1]
def queryPhone(self,name):
self.name = name
if name in self.phonedict:
... |
def list_files(dpath, pattern=None, extension=".nc", include=None, exclude=None, verbose=0):
"""
list_files list files in a folder according to patterns
Parameters
----------
dpath : string or pathlib.Path
The path to the files (str)
pattern : str, optional
The pattern to follo... |
#
# IndentWriter
#
# An indented text printer.
#
# Makes clever use of the semantics of the Python 2.5+ "with"
# statement to allow indented generator code to indent along
# with its indented output. This allows generator code to
# look much cleaner.
#
# (c) 2011 Lee Supe (lain_proliant)
# Released under the GNU Gen... |
#!/usr/bin/env python
import itertools
# A ring class - we use it to transpose our basic scale : C D E F G A B
class Ring:
def __init__(self, l):
if not len(l):
raise "ring must have at least one element"
self._data = l
def __repr__(self):
return repr(self._data)
def ... |
import re
text = 'abbaabbbbaaaaa'
pattern = 'ab'
for match in re.findall(pattern, text):
print ('Found {!r}'.format(match))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.