text stringlengths 37 1.41M |
|---|
## Print all fibonacci numbers <=n
def main():
n = int(input())
vals = [0,1]
while vals[-1]<=n:
num = sum(vals[-2:])
vals.append(num)
[print(x,end=' ') for x in vals[:-1]]
if __name__ == '__main__':
main() |
## Sum of all even-valued fibonacci terms below 4 million
def get_sum(num):
ans=2
val=0
a=1
b=2
while val<num:
val=a+b
a=b
b=val
if not val%2:
print(val)
ans+=val
return ans
def main():
MAX = int(input()) ## Max Range
ans = ge... |
## Print nth fibonacci number
def main():
n = int(input())
if n==1 or n==0:
print(n)
else:
vals = [0,1]
while len(vals)<=n:
num = sum(vals[-2:])
vals.append(num)
print(vals[-1])
if __name__ == '__main__':
main() |
## Find gcd of two numbers when one number is of order 10^250
def big_modulo(a,b):
small_mod = 0
for val in b:
big_mod = ((10*small_mod)%a+int(val)%a)%a
small_mod = big_mod
return big_mod
def get_gcd(a,b):
if b==0:
return a
return get_gcd(b,a%b)
def main():
t = int... |
# Given a number N, print all its unique prime factors and their powers in N.
def get_primes(num):
sieve = [True]*(num+1)
factors = {val:[] for val in range(num+1)}
for val in range(2,num+1):
if sieve[val]:
factors[val] = [val]
for mul in range(2*val,num+1,val):
... |
r"""
`RK methods <https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods>`_ on Wikipedia.
"""
import numpy as np
from ..misc.counter import Counter
def rk_1(y0, t, f, verbose=True, **_):
"""
RK1 or Explicit Euler method
:param array_like y0: Initial value, may be multi-dimensional of size d
:par... |
def check_repeat(row):
if len(row) != len(set(row)):
return False
return True
def check_elements(row, ref):
for item in row:
if item not in ref:
return False
return True
def row_wise(arr, ref):
for row in arr:
if check_elements(row, ref) == False or check_repe... |
def cal(name1,name2):
combStr = name1 + "loves" + name2
strCount = ""
for c1 in combStr:
if combStr.count(c1) != 0:
strCount+=str(combStr.count(c1))
combStr = combStr.replace(c1,"")
n= list(map(int,strCount))
while len(n)>2:
n = shortn(n)
... |
import numpy as np
from .util import pairwise_comparison_preference
def condorcet(P):
"""
Rule: Condorcet(P) : {x} if for all y in A \{x}, x net P over Y
Take the example:
a b c
b a c
c b a
a > c
b > c
b > a
Condorcet winner:
b
"""
A = np.unique(P)
highest_alter... |
Question 1
Print the first ArmStrong number in the range of 1042000 to 702648265 and exit the loop as soon
as you encounter the first armstrong number.
Use while loop
lower = 1042000
upper = 702648265
for num in range(lower, upper + 1):
# order of number
order = len(str(num))
# initialize sum
sum =... |
import datetime
from urllib.request import urlopen
from bs4 import BeautifulSoup, SoupStrainer
import ssl
import url
import re
"""
This code searches a page for instances of the user's keywords and creates a url object for each page with any of the keywords found.
To run, this code needs one parameter "url" that is th... |
class SaveData:
"""
Model for game's save file. Contains the data written or read from the file.
Kind of like a serializer.
"""
def __init__(self, ai_game):
"""Initialize 'save data' instance."""
self.ai_game = ai_game
def get_data(self):
"""Return data to be saved, ne... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 12 15:58:25 2019
@author: prashantpk
"""
# API KEY: 0299a321aad8b514e4873dff5b831681
# PRIVATE KEY: 5c7c66e8bfecdd1662bbaeafabfeb3ff
## Application ID: e7d78c18
## Application Key: 3b93ac98bf5e39f4e5a5dc09e9910c0a
_app_id = "e7d78c18"
_app_key... |
import random
import time
#
# BUBBLE SORT
#
def bubble_sort(lista):
for i in range(len(lista) - 1):
for j in range(len(lista) - i - 1):
if lista[j] > lista[j + 1]:
lista[j], lista[j + 1] = lista[j + 1], lista[j]
#
# INSERTION SORT
#
def insertion_sort(lista):
for i in rang... |
import sqlite3
from myfields import myfields
conn = sqlite3.connect('mydatabase.db')
c = conn.cursor()
def insert_record(rec):
with conn:
c.execute("INSERT INTO My_Table VALUES (:field1, :field2, :field3)", {'field1': rec.field1, 'field2': rec.field2, 'field3': rec.field3})
def get_all():
c.execute(... |
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import re
def dropStopWords(text):
text = re.sub("[^a-zA-Z]",' ',text)
text = text.replace(' x ','')
## text = text.replace(' ','')
word_list = text.split(' ')
filtered_words= word_list
## filtered_words = [word for wor... |
# ==============================
# NAME
# DATE
# CLASS
# HOMEWORK NUMBER
# PROGRAM DESCRIPTION
# ==============================
import sys
# ==============================================
# Beginning of the ADD FREQUENCIES function
# ==============================================
def add_frequencies(d,fi... |
def deb_card(card_num: str):
if type (card_num) == str and card_num.isdigit() and len(card_num)==16:
return f'Номер вашей карты катрты : **** **** **** {card_num[-4:]}'
else:
return ValueError
print(deb_card(input('')))
|
# one
shopping = {
"castorama" : ['deska', 'gwoździe', 'taśma', 'młotek'],
"ikea" : ['szafka', 'swieca', 'garnek'],
"sklep modelarski" : ['model fiata 126p']
}
shopping["sklep papierniczy"] = ['ryza papieru']
all = 0
for shop in shopping:
all = all + len(shopping[shop])
print("Idę do", shop.capita... |
# Introducción a Python
## Acerca de Python
Python es...
* **libre** – es software distribuible de código abierto
* **fácil de aprender** – tiene una sintaxis de lenguaje simple
* **fácil de leer** – no está atiborrada de signos de puntuación
* **fácil de manterner** – es modular para simplicidad
* **“baterias inclu... |
'''
Problem: Tower of Hanoi
Statement: Given an tower of height n, how do you move
the disks to a 3rd peg, making sure all disks
are in increasing size.
'''
class Tower:
def __init__(self, n):
self.one = [x for x in range(n)]
self.two =... |
'''
Problem: Largest Non-Adjacent Sum
Statement: Given an input array x, return the largest possible sum of
non-adjacent elements in the array. Numbers can be 0 or
negative.
Example:
Input: [5,1,1,5]
Output: 10
Explanation:
5+5 = 10
'''
from typ... |
#!/usr/bin/env python
# coding: utf-8
# In[23]:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
csv_data_file=pd.read_csv('/home/greesh/Documents/verdatumcode/Democracy-Dictatorship_Index.csv')
data=csv_data_file.set_index('Regime')['Type'].to_dict()
democracy=[]
dictatorship=[]
count=0
for ... |
import pygame
class Snake:
n_added = 1 # Number of items to add to the snake when it lengthens
def __init__(self, length, x_max, y_max, step):
self.step = step
self.length = length # Initial length of the snake
self.x_max = x_max
self.y_max = y_max
self._image_surf =... |
class Car:
def __init__(self, name, year):
self.name = name
self.year = year
def display(self):
print("My car model name is {} and buld in year {}".format(
self.name, self.year))
c1 = Car("Toyota", 25)
c1.display()
|
from tkinter import *
import pandas
import random
BACKGROUND_COLOR = "#B1DDC6"
current_card ={}
to_learnDict = {}
#reading data from pandas
try:
data = pandas.read_csv("data/words_to_learn.csv")
except FileNotFoundError:
data = pandas.read_csv("data/french_words.csv")
to_learnDict = data.to_dict(orient="re... |
#!/usr/bin/env python3
# Given 2 strings, how many characters must you delete to make the two strings anagrams of each other
import math
import os
import random
import re
import sys
from collections import Counter
def makeAnagram(a, b):
count_a = Counter(a)
count_b = Counter(b)
count_a.subtract(count_b)
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 20 12:50:26 2019
@author: Ahmad ALaarg
"""
"""
1-Write a Python program to accept 2 numbers from the users and print the greatest
"""
#-----------------------------------------------------
"""
x = int(input('enter your first number '))
y = int(input('enter your sucend n... |
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 21 09:37:20 2019
@author: Ahmad ALaarg
"""
"""
s1= 'hello orange academy'
print ( s1 )
print ( s1[0 ])
print ( s1[ 2])
print ( s1[2:10])
print ( s1[5:])
print ( s1 * 2)
print ( s1.capitalize ())
print ( s1.upper ())
print (s1.center(20 ))
print (s1.replace('Orange', 'A... |
# NLP assignment 3 - POS Tagging
# Austin Beggs - 3/8/2019
# The goal of this program was to take in training data and apply POS tags to a text file
# based on probabilities of tags from the training data. Actual training input was included in
# the pos-test and pos-train text files. To run this program you must in... |
start_list = [5, 3, 1, 2, 4]
square_list = []
for list in start_list:
quadrado = list ** 2
square_list.append(quadrado)
square_list.sort()
print square_list
|
from random import randint #Importar random de randint
#Variavel responsavel pelo tabuleiro
board = []
#Laco para criar uma grade 5x5, inicializado com 'O's em todas as posicoes do tabuleiro
for x in range(5):
board.append(["O"] * 5)
#Mostra se o tabuleiro foi criado
#print board
#Funcao identificada para per... |
import time
def bubbleSort(array, drawArr):
if len(array) == 1:
return array
l = len(array)-1
while l != 0:
for i in range(l):
if array[i] > array[i+1]:
array[i], array[i+1] = array[i+1], array[i]
drawArr(array, ["pink" if x == i or x == i +
... |
#PYTHON DICTIONARY
import randomfunctions
books ={
"novels": "things fall a part",
"science" : "Physics text",
"motivational" : "Richest man in babylon",
}
print(books["novels"])
#updating the values
books["motivational"] = "think big"
print(books)
#printing the values of dict using a loop
for x in books.v... |
"""
CODILITY DEMO
A non-empty array A consisting of N integers is given. The array contains an odd number
of elements, and each element of the array can be paired with another element that
has the same value, except for one element that is left unpaired.
For example, in array A such that:
A[0] = 9 A[1] = 3 A[2]... |
#mutli-level inheritance
class Animals:
def livinfthings(self):#TOP LEVEVL PARENT CLASS
print("Animals are living things")
class Dogs(Animals):
def response(self):
print("Animals like dogs bark")
class puppies(Dogs): #CHILD CLASS
def nutrition(self): # METHOD
print("Animals like d... |
#basic python
import datetime
today = datetime.date.today()
print("Today date is :", today)
print (' ')
'''Loopoing - control flow in python '''
#WHILE
i = 0
while (i <= 5):
print ('The value of while loop :', i)
if(i == 5):
break
else:
i += 1
#FOR
for i in range(5):
... |
totalValidPasswords = 0
with open('advent2020/day2/day2input.txt', 'r') as file:
for testPassword in file.readlines():
rangeAndLetter = testPassword.split(':')[0]
letter = rangeAndLetter[-1]
num1 = int(rangeAndLetter.split('-')[0])
num2 = int(rangeAndLetter.split('-')[1].strip(letter... |
from typing import List
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
first_zero_index = None
for i in range(len(nums)):
if nums[i] == 0:
if first_zero_index is None:
first_zero_index = i
elif first_zero_index is not None... |
from typing import List, Optional, Tuple
Interval = Tuple[int, int]
def overlap(intx: Interval, inty: Interval) -> Optional[Interval]:
xs, xe = intx
ys, ye = inty
if xs <= ye and ys <= xe:
return max(xs, ys), min(xe, ye)
class Solution:
def intervalIntersection(
self,
firstL... |
from typing import List
from string import ascii_lowercase
class Solution:
def letterCasePermutation(self, s: str) -> List[str]:
stack = [""]
s = s.lower()
while stack:
w = stack.pop()
if len(w) == len(s):
yield w
else:
if... |
from typing import List, Optional
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if ro... |
from typing import Optional
class MyQueue:
def __init__(self):
self._left = []
self._right = []
def _rebalance(self):
right = self._right
take = max(len(right) >> 1, 1)
self._left = right[:take][::-1]
self._right = right[take:]
def push(self, x: int) -> No... |
from typing import List
from collections import Counter
Board = List[List[str]]
VALID_CHARS = ".123456789"
class Solution:
def isValidSudoku(self, board: Board) -> bool:
def validate(xs: List[str]) -> bool:
seen = set()
for x in xs:
if x not in VALID_CHARS or (x !... |
from typing import Any, Iterable, Optional
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def iter_tree(root: Optional[TreeNode]) -> Iterable[Any]:
CALL, HANDLE = 0, 1
call_s... |
from typing import List
class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
if triangle:
min_path = triangle[-1].copy()
for i in range(len(triangle) - 2, -1, -1):
for j in range(len(triangle[i])):
min_path[j] = triangle[i][... |
from typing import Optional
from itertools import repeat
# Definition for a Node.
class Node:
def __init__(
self,
val: int = 0,
left: "Node" = None,
right: "Node" = None,
next: "Node" = None,
):
self.val = val
self.left = left
self.right = right
... |
from collections import OrderedDict
class Solution:
def firstUniqChar(self, s: str) -> int:
seen = set()
ordered_map = OrderedDict()
for i in range(len(s) - 1, -1, -1):
char = s[i]
if char not in seen:
ordered_map[char] = i
elif char in o... |
# Autor:Andersson Sanabria
# Fecha:15/04/2021
# Version:1.0
# Nombre del Proyecto:Ejercicio #9
# ----------------------Ejercicio #9-----------------------------
# Escribir un programa que solicite ingresar su nombre y edad, luego los almacene,
# y los muestre en pantalla, mediante la funcion f-string, luego utilizar... |
def primos(n):
es_prim=True
if n % 1 == 0:
for values in range(2,n-1):
if n % values==0:
es_prim=False
return es_prim
if __name__=='__main__':
n=int(input('escribe un numero: '))
primo=primos(n)
if primo==True:
pr... |
# Autor:Andersson Sanabria
# Fecha:28/04/2021
# Version:1.0
# Nombre del Proyecto:Ejercicio #7
# ----------------------Ejercicio #7-----------------------------
# Escribí un programa que solicite al usuario que ingrese cuántos shows musicales
# ha visto en el último año y almacene ese número en una variable. A contin... |
class PaymentTypes():
def __init__(self):
self.paymentTypes = {
"Efectivo": 10,
"Cheque": 11,
"CreditCard local": 12,
"CreditCard online": 13
}
def paymentTypesIs(self, types):
if types in self.paymentTypes.keys():... |
import re
import pandas as pd
import time
import datetime
def StringToDatetime(s):
"""
Check whether the string s is a time format string.
return datetime or s
Example: '2014/02/03' return '%Y/%m%d'
'2014-02-03 00:00:00' return '%Y-%m-%d %H:%M:%S'
"""
if type(s) != str and type(s)... |
# -*- coding:UTF-8 -*-
import random
import pprint
from copy import deepcopy
pp = pprint.PrettyPrinter(width=20)
A = [[1,2,3],
[2,3,3],
[1,2,5]]
B = [[1,2,3,5],
[2,3,3,5],
[1,2,5,1]]
#生成一个r行c列矩阵
def random_matrix(r,c):
m = [[0]*c for row in range(r)]#初始化r行r列的0矩阵
for e in m:
for i in range(len(e)):
e[i] ... |
# ================================================
# Hangman Game
# ================================================
# Here's a hangman game made by Vincent J. U.
# How it works : the hidden words are saved in variable:words in which is randomly copied from variable:collection.
# user's answer will be ... |
print("Welcome! type any number.")
print("type \"quit\" to exit")
if exit != 0:
loop=0
loop = 1
while loop == 1:
x = input("--> ")
if x != "quit" :
x = int(x) #converts to integer
if x > 0:
print("input is greater than 0!")
if x < 100:
print("input is also less th... |
#!/bin/python3
#print string
print ("strings and things")
print ('hello0o0o')
print (''' hello
this is a multi line string''')
print ("this is "+" a string")
print ('\n') # new line
#math
print ("math time")
print (5+5) #add
print (5-5) #subtract
print (5*5) #multiply
print (5/5) #division
print (5+5-5*5/5)... |
a = 10
b = 20
def display():
print("Hello to the functions")
display()
def add():
a = 10
b = 20
c = a + b
print("Addition is",c)
add()
def sub():
c = a - b
print("Subtraction is",c)
sub() |
import time
start = time.time()
a = []
for i in range(0,100000000):
a.append(i)
##print(a)
end = time.time()
print("Time", end-start)
|
a = [1,2,3,"Hello",10.5,True,120.00000]
print(a)
print(a[-1])
print(a[::-1])
print(a[:-1])
b = "Hello","Python"
print(b)
|
def add(num_1,num_2):
return num_1 + num_2
def sub(num_1,num_2):
return num_1 - num_2
def div(num_1,num_2):
return num_1 / num_2
def mul(num_1,num_2):
return num_1 * num_2
def mainFunction():
while True:
print("""
1. Add
2. Sub
3. Div
4. Mul
""")
user_ch... |
def division():
a = int(input("Enter a number: "))
b = a/2
try:
assert(b > 0 ), "Try Again"
print("Result is ",b)
except AssertionError as er:
print(er)
division()
|
a = input("Enter first number : ")
b = input("Enter Second number : ")
c = int(a) + int(b)
print("Sum is",c) |
thislist=["hello man",12548696,"We go out"]
print(type(thislist))
print(thislist[0])
print(thislist)
print("######Writing diff #######")
for items in thislist:
print(items)
#lets see operations in a list
print("###### operations in the list #######")
#Change the second item:
thislist[1]=365489652
print(thislist)
#che... |
def search(arr, left, right):
obj = {}
for i in arr:
if i not in obj:
obj[i] = 1
else:
obj[i] += 1
tar = max(obj.values())
if tar > len(arr)/2:
return 1
return 0
n = int(input())
num_list = []
num_list.append(list(map(int,input().split())))
i = sear... |
x = 3
y = 10
if x == y:
print('X and Y are equal')
else:
if x > y:
print('X is greater than Y')
else:
print('X is less than Y')
###############################################
hours = input('Enter hours : ')
rate = input('Enter rate : ')
if float(hours) > 40:
pay = float(hours) * flo... |
class Node():
def __init__(self, data):
self.data = data
self.next = None
def __str__(self):
return str(self.data)
class LinkedList():
def __init__(self):
self.head = None
self.tail = None
def addNode(self, data):
temp = Node(data)
if self.head == None:
self.head = temp... |
import random
sides = 0
rolls = 0
roll_count = 0
print("This program is a simple dice roll program.")
input("press enter to continue...")
sides = int(input("How many sides do you want the dice to have? "))
rolls = int(input("How many dice do you want to roll? "))
while roll_count < rolls:
print(rando... |
# Поработайте с переменными, создайте несколько, выведите на экран,
# запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран.
a = "a"
b = 1
c = True
print(a)
print(b)
print(c)
d = input("Введите число ")
print(f"Введенное число {d}")
e = input("Введите строку ")
print("Введенная... |
import itertools
import random
m_list = []
t_list = []
for i in itertools.count(97):
m_list.append(random.randint(i, 122))
if len(m_list) > 5:
print(m_list)
break
for j in itertools.cycle(m_list):
t_list.append(chr(j))
if len(t_list) > 2 * len(m_list):
print(t_list)
br... |
# Пользователь вводит строку из нескольких слов, разделённых пробелами.
# Вывести каждое слово с новой строки.
# Строки необходимо пронумеровать.
# Если в слово длинное, выводить только первые 10 букв в слове.
text = input("Опишите себя: ")
list = text.split()
print("Вы утверждаете, что: ")
for i in range(len(list))... |
import random
# Направления
DIRS = ("Лево", "Право", "Назад")
class Car:
def __init__(self, speed, color, name, is_police):
self.speed = speed
self.color = color
self.name = name
self.is_police = is_police
def go(self):
print(f"{self.name} поехала")
def stop(self)... |
class MComplex:
def __init__(self, x: float, y: float):
self.x = x
self.y = y
def __add__(self, other):
return MComplex(self.x + other.x, self.y + other.y)
def __mul__(self, other):
# (x1x2 - y1y2) + (x1y2 + x2y1)i
x = self.x * other.x - self.y * other.y
y =... |
"""
Veti primi un numar intreg de la tastatura.
Va trebui sa spuneti daca acel numar este palindrom, folosind tipul de date
boolean (True, False)
Observatii:
- palindrom: numarul este acelasi de la stranga la dreapta,
si de la dreapta la stanga
exemplu:
Veti primi: 12321
... |
"""
Finding a Motif in DNA
"""
import fileinput
line_list = []
for line in fileinput.input("rosalind_subs.txt"):
line_list.append(line.strip())
dna_string = line_list[0]
dna_substring = line_list[-1]
#get 1st position and position - length of the substring
for x in range(0, len(dna_string)-len(dna_substring)):
if... |
# 암호걸린 PDF 파일 불러오기
import PyPDF2
pdfFile = open('encrypted.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFile)
#값을 붙여넣을 빈 객체를 생성
pdfWriter = PyPDF2.PdfFileWriter()
# 암호를 입력하지 않으면 에러가 발생합니다.(암호:rosebud)
pdfReader.decrypt('rosebud')
for pageNum in range(pdfReader.numPages):
pdfWriter.addPage(pdfR... |
#!/usr/bin/env python3
import sys
import glob
import os
# Read multiple text files
inputPath = sys.argv[1]
output_file = sys.argv[2]
for input_file in glob.glob(os.path.join(inputPath,'*.txt')):
print(os.path.basename(input_file))
print("-------------------------------")
with open(input_file,... |
age = input("생후 몇개월: ")
age = int(age)
if 0 <= age <= 1 :
print("결핵 접종")
if 0 <= age <= 2 :
print("B형 간염 접종")
if 2 <= age <= 6 :
print("파상풍 접종")
if 2 <= age <= 15 :
print("폐렴구균접종")
|
field = [["-" for j in range(3)] for i in range(3)] #предупреждаю код ужасен)) не знаю как улучшить(
def find_tire():
check = 0
for row in field:
for elem in row:
if elem == "-":
check += 1
return check
def win(x):
for i in range(len(field) - 1):
if field[i... |
# Задача-1:
# Дан список, заполненный произвольными целыми числами, получите новый список,
# элементами которого будут квадратные корни элементов исходного списка,
# но только если результаты извлечения корня не имеют десятичной части и
# если такой корень вообще можно извлечь
# Пример: Дано: [2, -5, 8, 9, -25, 25, 4] ... |
#Pulls the data from the api with a start and end date
def api_search(code,start,end):
url="http://api.worldweatheronline.com/premium/v1/past-weather.ashx?key=6230647e6745477995c00355202410&q="+code+"&format=json&date="+start+"&enddate="+end +"&tp=24"
return url
import json
import urllib.request
import re
#a... |
def main() :
comm = input("Please specify a command [list, add, mark, archive]: ")
if comm == "add" :
add()
if comm == "list" :
listw()
if comm == "mark" :
mark()
if comm == "archive" :
archive()
def listw() :
fr = open ('todolist', 'r')
i = 1
pri... |
#PROGRAMA 18
#Ejercicio 18 condicional doble
import os
dias=0
#INPUT VIA OS
dias=int(os.sys.argv[1])
#processing
#Si el producto supera los 22 dias
#aplicar descuento
descuento=dias>22
if(dias>22):
print("con descuento")
else:
print("sin descuento")
#finif
|
import random
EASY_LEVEL_ATTEMPTS = 10
HARD_LEVEL_ATTEMPTS = 7
def check_answer(guess,random_number):
if guess < random_number:
print("Too low")
elif guess > random_number:
print("Too high")
elif guess == random_number:
print("You've won!")
def set_difficulty(difficulty):
if difficulty == 'easy... |
# write a program that reads character one by one and store them in UPPER if in upper case or in LOwer if in other.
def convertOpposite(str):
ln = len(str)
for i in range(ln):
if str[i] >= 'a' and str[i] <= 'z':
# Convert lowercase to uppercase
str[i] = chr(ord(str[i]) -... |
# Write a program that recieves 4 digit no. and calculate sum of squares of first 2 digits and last 2 digits.
import math
def sum_of_squares(number):
x = int(number[0:2])
y = int(number[2:5])
z = math.pow(x, 2)+ math.pow(y, 2)
print(f"the sum of the square of the two numbers is {z}.")
number = inpu... |
# Glossary
# Indentation https://www.learnpython.org/en/Hello,_World!
# Variables and Types https://www.learnpython.org/en/Variables_and_Types
# Numbers
# Strings
# Lists
# Basic Operators https://www.learnpython.org/en/Basic_Operators
# Arithmetic Operators
# Using Operators with Strings
# Usi... |
#import matplotlib
from matplotlib.pyplot import figure, show
import matplotlib.pyplot as plt
from numpy import arange, sin, pi, cos, tan
import numpy as np
import math
def a1(x,a,b,c,d):
return a*sin(b*x+c)+d
def a2(x,a,b,c,d):
return a*cos(b*x+c)+d
def a3(x,a,b,c,d):
return a*tan(b*x+c)+d
if __name__... |
import numpy as np # multi-dimensional arrays
from PIL import Image # images
import matplotlib.pyplot as plt # used to display a matrix as an image
#-------------------------------------------------
# Utility functions for images.
#
# An image is represented as a 3-dimensional array of unsigned
# integers. Th... |
#!/usr/bin/env python3
sz1 = 23
sz2 = 9
tipp = int(input ('Mennyi ' + str(sz1) + '+' + str(sz2) + ' ? '))
if tipp == sz1 + sz2:
print ('Nem rossz, nem rossz...')
else:
print('Háát mit csinálsz?!')
|
# -*- coding: utf-8 -*-
__author__ = 'Benjamin Grandfond <benjaming@theodo.fr>'
class Toilet:
FREE = 'free'
USED = 'used'
def __init__(self, name, captor, status=True):
self.name = name
self._captor = captor
self._status = self.convert_status(status)
def __unicode__(self):... |
from cs50 import get_int
while True:
n = get_int("Positive number: ")
if n > 0:
break
for i in range(n):
for j in range(n-i):
print(" ", end="")
for k in range(i+1):
print("#", end="")
print()
|
"""Functions for common math operations."""
def add(num1, num2):
"""Return the sum of the two inputs."""
addition = num1 + num2
return addition
def subtract(num1, num2):
"""Return the second number subtracted from the first."""
sub = num1 - num2
return sub
def multiply(num1, num2):
"... |
#Given an array nums and a value val, remove all instances
#of that value in-place and return the new length.
#Do not allocate extra space for another array, you must do this by
#modifying the input array in-place with O(1) extra memory.
#The order of elements can be changed. It doesn't matter what you leave beyond... |
def safe_pawns(pawns):
pawns = list(pawns)
count = 0
for i in pawns:
ad1 = chr(ord(i[0])-1) + str(int(i[1])-1)
ad2 = chr(ord(i[0])+1) + str(int(i[1])-1)
if ad1 in pawns or ad2 in pawns:
count += 1
return count
print(safe_pawns({"b4", "d4", "f4", "c3", "e3",... |
"""
This module contains classes to be used to read a LilyPond .notes file
created using an events listener. The events are parsed into a set of
Notes which are held in Voices (think instrument or choral part). The
voices are held in a Score, which does the main parsing work.
"""
class Note:
"""... |
#defining function for getting tripltes
def func(a, n):
found =False
for i in range(0, n - 2):
#creating range
for j in range(i + 1, n - 1):
for k in range(j + 1, n):
if (a[i] + a[j] + a[k] == 0):
print( a[i], a[j], a[k])
fou... |
class DisWords:
def __init__(self):
pass
def measureWords(self, wA, wB):
lenMin = min(len(wA), len(wB))
lo = -1
for i in range(1, lenMin):
if(i < lenMin and wA[-i:-1] + wA[-1:] == wB[0:i]):
lo = i
i = i + 1
if lo == -1:
... |
i = 1
while i < 31:
if i % 15 == 0:
print("TanaWaii!")
elif i % 3 == 0:
print("Tana!")
elif i % 5 == 0:
print("Waii!")
else:
print(i)
i += 1 |
# Uses python3
import sys
def get_max_pairwise_sum(n):
pairs = list()
pairs.append(1)
temp = 2
while n != 0:
if n > (temp * 2):
pairs.append(temp)
n -= temp
temp += 1
else:
pairs.append(n)
break
print(len(pairs))
for x ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.