text stringlengths 37 1.41M |
|---|
import random
class Deck():
'''
Represents a deck of 52 cards.
'''
def __init__(self):
class Card():
'''
Represents and individual card of a deck with attributes of a face (or number), suit, and value.
'''
def __init__(self, suit, value, face):
... |
# constants
coins = [0.25, 0.1, 0.05, 0.01]
def main():
print(round(calc_change(get_input(), coins)))
def get_input():
"""Return positive float number as valid user input"""
while True:
try:
cash = float(input("Change owned: "))
except ValueError:
continue
... |
# -*- coding: utf-8 -*-
import urllib2
import urllib
import json
key = "39c4e5aceb68dafb76cddbdfdecf5520"
#pernw tis suntetagmenes
x = input("Geografiko platos?: ")
y = input("geografiko mhkos?:")
#metatroph tou float number h int pou tha eiselthei stis suntetagmenes se string
x = str(x)
y = str(y)
... |
import os
#分岐確認
var_ = 9
if var_ < 10:
print("10未満")
else:
print("10以上")
#現在ディレクトリの一つ上のディレクトリ一覧を取得
for i in os.listdir("../"):
print(i) |
def funcao_numero(num = 0):
ultimo = num
primeiro = 1
while True:
for c in range(1,primeiro + 1):
print(f'{c} ',end=' ')
print()
primeiro += 1
if primeiro > ultimo:
break
num = int(input('Informe um número para ver uma tabela personaliada: '))
funcao_... |
# Python program to implement Diffie-Hellman key exchange
import random
def is_prime(n):
count = 0
for i in range(1, int(n/2)+1):
if (n % i == 0):
count += 1
if (count == 1):
return True
else:
return False
while(True):
p = int(input("Enter a prime number : "))
... |
# Python program to generate pseudo-random numbers using the middle square method
seed = int(input("Enter a 4 digit number : "))
number = seed
print(f"The seed is {seed}.")
print("The random numbers are : ")
already_generated = set()
while(True):
already_generated.add(number)
Xi = str(int(number)**2)
#... |
from typing import Optional
class Node(object):
left: "Node"
right: "Node"
data: int
def __init__(self, data, left, right):
self.data = data
self.left = left
self.right = right
class BST(object):
root: Optional[Node]
size: int
def __init__(self):
self.ro... |
import random
import numpy as np
import pynmmso as nmmso
class Swarm:
"""
Represents a swarm in the NMMSO algorithm.
Arguments
---------
id : int
Id used to refer to the swarm
swarm_size : int
Maximum number of particles in the swarm
problem :
Instance of the prob... |
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A, K):
"""Shifts each value in A K times
:param A: Input array (int)
:param K: Number of shifts
:returns: new shiftes array [Int]
:rtype: Array (int)
"""
# write your code in Python 3.6... |
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
return self.val
class Solution(object):
def oddEvenList(self,head):
head2=head.next
h1=head
h2=head2
while h1 and h2:
h1.next= h2.next
... |
from leetcode import TreeNode
class Solution(object):
def hasPathSum(self, root, sum):
if not root:
return False
if root.val==sum and root.left==None and root.right==None:
return True
else:
return self.hasPathSum(root.left,sum-root.val) or \
... |
# Definition for a binary tree node.
from leetcode import TreeNode
class Solution(object):
def levelOrderBottom(self, root):
if not root:
return []
res=[]
nodequeue1=[]
res.append([root.val])
nodequeue1.append(root)
nodequeue2=[]
while nodequeue1... |
from list import createlist
class Solution(object):
def removeNthFromEnd(self, head, n):
if n==1 and head.next==None:
return None
n=n-1
p=head
while n>0:
p=p.next
n-=1
if p.next:
self.deleteNode(p)
else:
p... |
from leetcode import ListNode
def createlist(data):
h=ListNode(data[0])
p=h
for item in data[1:]:
p.next=ListNode(item)
p=p.next
return h
def printlist(head):
ls=[]
while head:
ls.append(head.val)
head=head.next
print(ls)
|
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
return self.val
class Solution(object):
def deleteDuplicates(self, head):
p=head
while p and p.next:
if p.val==p.next.val:
self.deleteNode(p)
... |
#!/usr/bin/python
import sys
# input from standard input
i = 0
for line in sys.stdin:
line = line.upper()
print line
# # remove whitespaces
# line = line.strip()
# # split the line into tokens
# tokens = line.split()
#
# for token in tokens :
# i = i + 1
# # write the results to standard output
# print '%s\t%s' %... |
# -*- coding: utf-8 -*-
"""
/************************ TESTE DE PERFORMANCE 03 **************************
* Questao 18 *
* Aluno : Francisco Alves Camello Neto *
* Disciplina : Fundamentos do Desenvolvimento Pyt... |
# -*- coding: utf-8 -*-
"""
/************************ TESTE DE PERFORMANCE 03 **************************
* Questao 12 *
* Aluno : Francisco Alves Camello Neto *
* Disciplina : Fundamentos do Desenvolvimento Pyt... |
import random
from random import randint
def is_monotonic(nums):
result = False
increases = 0
decreases = 0
len_nums = len(nums)
for i in range(len_nums - 1):
if nums[i] > nums[i + 1]:
decreases += 1
elif nums[i] < nums[i + 1]:
increases += 1
... |
#Loops - repetitive tasks
for number in range(10): #iterate through sequence of numbers
print(number)
for num in range(5):
print(num)
for num in range(1,11,2):
print(num)
# Use for loop to print numbers 0 to 100 (inclusive)
for num in range(101):
print(num)
#Use for loop to print numbers 0 to 100 ... |
# Q1) Write a function that takes a temperature in fahrenheitand returns the temperature in celsius.
# Fahrenheit to Celsius formula: (°F – 32) x 5/9 = °C
# def convert_temperature(fahrenheit):
# '''Convert fahrenheit to celsius'''
# return (fahrenheit - 32) * 5.0/9.0
# print(convert_temperature(350))
# Q2) ... |
from functools import wraps
from time import time
def timing(f):
@wraps(f)
def wrap(*args, **kw):
ts = time()
result = f(*args, **kw)
te = time()
print("func %r args:[%r, %r] took: %2.4f sec" % \
(f.__name__, args, kw, te-ts))
return result
return wrap... |
def combine_skipper(f, lst):
"""
>>> lst = [4, 7, 3, 2, 1, 8, 5, 6]
>>> f = lambda l: sum(l)
>>> lst = combine_skipper(f, lst)
>>> lst
[11, 1, 3, 2, 9, 5, 5, 6]
>>> lst2 = [4, 3, 2, 1]
>>> lst2 = combine_skipper(f, lst2)
>>> lst2
[7, 1, 2, 1]
"""
n = 0
while n < len(... |
# _*_ coding:utf8-
from math import *
from random import *
'''
#1.数学方面: 五角数
def getpen(n):
n=n*(3*n-1)/2
print("%.0f"%(n),end=" ")
s=0
for i in range(1,101):
getpen(i)
s=s+1
if(s%10==0):
print('')
'''
'''
#2.求一个整数各个数字的和
def sumdigits(n):
s=0
while(n%10!=0):
... |
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
length = len(nums)
k = k % length
if k < 0:
k=k+length
self.reverse_array(nums,0,length-1)
self.reverse_array(nums,0,k-1)
self.reverse_array(nums,k,length-1)
def ... |
def moves_begin_zero(array):
if len(array) < 1:
return
length = len(array)
#we will assing the pointers of read and write index
r_ind = length-1
w_ind = length-1
#creating a loop where if read index is not zero, the read index value is stored in write index and write index is d... |
def solution(dataset, a, b, c):
result=[] #initialize empty matrix to store transformed values
for i in range(len(dataset)): #loop to solve equation for each value of x
sol=a*(dataset[i]**2)+b*dataset[i]+c
result.append(sol) #store f(x) values in result array
b = sorted(result) #sort array ... |
l = ["big", "name", "happy", "hey", "give", "root", "doggy", "man", "sixer"]
def capitalize_nested(l):
n= []
for str in l:
n.append(str.upper())
return n
print(capitalize_nested(l))
|
import unittest
def is_leap_year(year):
# うるう年の判定をしてみましょう
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
return True
else:
return False
class TestLeapYear(unittest.TestCase):
def test_is_leap_year_4(self):
"""4の倍数の年のテスト."""
self.assertTrue(is_leap_year(2020)... |
def Reverse():
while True:
A = input("Enter Your Text You Want To Reverse >>>")[::-1]
print(A)
Reverse()
|
class Ninja():
def __init__(self, first_name, last_name, pet, pet_food, treats):
self.first_name = first_name
self.last_name = last_name
self.pet = pet
self.pet_food = pet_food
self.treats = treats
def walk(self, Pet):
Pet.play()
return self
def feed... |
class Rectangle:
def __init__(self,width,height):
self.set_width(width)
self.set_height(height)
def __str__ (self):
return "Rectangle(width="+str(self.width)+", height="+str(self.height)+")"
def set_width(self,width):
self.width=width
def set_height(self,height):
... |
# Models the number of new teams on each show of the BBC gameshow "Pointless"
# There are 4 teams on each episode.
# Teams get two chances to win the gameshow
# If a team wins the show they are replaced by a new team next episode
# If a team loses two episodes they are replaced by a new team next episode
# This progr... |
"""
Given an array, find the int that appears an odd number of times.
There will always be only one integer that appears an odd number of times.
"""
#My solution, lol not Pythonic at all fml
def find_it(seq):
l = len(seq)
count = 0
for y in seq:
for x in seq:
if y == x:
... |
n = int(input())
words = []
for _ in range(n):
words.append(input())
words = list(set(words))
words.sort(key=lambda x:(len(x),x))
for w in words:
print(w) |
import sys
# 중복되는 것 제거한 풀이 : 틀림 ㅠㅠ
word = sys.stdin.readline().split()
lower_word = list(map(lambda x: x.lower(),word))
lower_word = set(lower_word)
print(len(lower_word))
# 중복되는 것도 모두 세기
word = sys.stdin.readline().split()
print(len(word)) |
def solution(n):
n = sorted(str(n),reverse=True)
answer = ''
for i in n:
answer += i
return int(answer)
# ls = list(str(n))
# ls.sort(reverse = True)
# return int("".join(ls)) |
"""
단, 코스요리 메뉴는 최소 2가지 이상의 단품메뉴로 구성하려고 합니다.
또한, 최소 2명 이상의 손님으로부터 주문된 단품메뉴 조합에 대해서만 코스요리 메뉴 후보에 포함하기로 했습니다.
"""
from itertools import combinations
def solution(orders, course):
# course의 수만큼 combination 있는지 확인.
dictionary = {}
for order in orders:
order = sorted(order)
for cnt in course:
... |
# stack
def solution(s):
stack = []
for i in s:
if not stack:
stack.append(i)
continue
if stack[-1] == i:
stack.pop()
else: # 어떻게 이 부분을 까먹니! 담에는 좀 더 꼼꼼히 살펴보자
stack.append(i)
return 0 if stack else 1
print(solution('baabaa'... |
# 정렬할 변수
x = [3,6,2,8,1,4,9,10]
# 버블정렬 Bubble Sort
def bubble_swap(x, i, j):
x[i], x[j] = x[j], x[i]
def bubbleSort(x):
for size in reversed(range(len(x))):
for i in range(size):
if x[i] > x[i+1]:
bubble_swap(x, i , i+1)
# print(list(reversed(range(len(x)))))
# [7, 6, 5, 4... |
def solution(n):
answer = ''
while n > 0:
a, b = n // 3, n % 3
answer += str(b)
n = a
# 0021
result = 0
for i in range(len(answer)):
result += (3**i)*int(answer[::-1][i])
return result
print(solution(125))
# 다른 사람 풀이
def solution2(n):
tmp = ''
while n:
... |
# Algorithm to move all the negative element to front
"""
EXAMPLE:
INPUT : [1, 2, -3, -5, -3, 1, 4, 6, -5, 3]
OUTPUT : [-5, -3, -3, -5, 2, 1, 4, 6, 1, 3]
"""
"""
------------------------------------IMPORTANT NOTE------------------------------------------------
I also solved this problem using 2 pointe... |
from math import sin, cos
theta = 0
theta_max = 3.14 / 2
theta_rmax = 0
d_theta = 0.01
dt = 0.001
g = 9.81
range_max = -1
v = 8.29
while theta < theta_max:
y = 1.5
x = 0
t = 0
while y > 0:
y = y + v*sin(theta)*t - 0.5*g*t*t
x = v*cos(theta)*t
t = t +... |
# 10までの3と5の倍数の和は、
# 3の倍数: 3 6 9
# 5の倍数: 5 10
# = 33
#
#
# 10000000の場合の和は?
#target = 1000
def multiple(thistarget = 10000000):
summary_three = 0
summary_five = 0
summary_total = 0
for f in range(0,thistarget+1,3): #1000万までの3の倍数を合計する
summary_three += f
print(summary_three)
for ff in range(0,... |
#script que calcula la tambla de multiplicar de un número
numero = input('que numero quieres multiplicar?')
# el dato ingresado por el usuario es una cdena "<str>"
# Se debe convertir a numero "<int>" para poder multiplicar
numero=int(numero)
for n in range(10):
r = numero * (n + 1)
print(r)
|
def combination(n, m):
if m == 0 or n == m:
return 1
return combination(n-1, m-1) + combination(n-1, m)
while True:
try:
n = int(input("집합의 모든 원소의 갯수를 입력하세요: "))
m = int(input("고르는 원소의 갯수를 입력하세요: "))
if n <= 0 or m <= 0:
print("원소의 개수가 0보다 작습니다. 다시 입력해주세요.")
... |
"""
将ISBN号去重,并使用冒泡排序从小到大排序
输入:
10
9781234567890
9781241242123
9782141241223
9784689622528
9786904328539
9783462839468
9783849534054
9783426989053
9784032698743
9783462839468
输出:
9781234567890
9781241242123
9782141241223
9783426989053
9783462839468
9783849534054
9784032698743
9784689622528
9786904328539
"""
in_num = ... |
"""
将ISBN号去重,并使用快速排序从小到大排序
输入:
10
9781234567890
9781241242123
9782141241223
9784689622528
9786904328539
9783462839468
9783849534054
9783426989053
9784032698743
9783462839468
输出:
9781234567890
9781241242123
9782141241223
9783426989053
9783462839468
9783849534054
9784032698743
9784689622528
9786904328539
"""
def qui... |
user_number = int(input("Введите число:"))
double_number = user_number * 10 + user_number
triple_number = double_number * 10 + user_number
summ = user_number + double_number + triple_number
print(f" {user_number} + {double_number} + {triple_number} = {summ}")
|
#########################################################################
###### Name: Kenneth Emeka Odoh
###### Purpose: An example of using the Recursive Linear Regression
#########################################################################
from __future__ import division
import pandas as pd
import numpy as np... |
# Ваш первый код на Python
# Задание 1
# С этого задания вы начинаете создавать собственного персонального помощника,
# вроде Алисы, Google Assistant, Siri или Alexa. Назовём её Анфиса.
# Для начала научите Анфису здороваться: код уже подготовлен, но Python не станет его выполнять,
# ведь он скрыт за символом коммент... |
# Задача 1
# Доработайте программу подсчёта тёплых дней в мае 2017 г. : допишите функцию comfort_count()
# так, чтобы она возвращала подсчитанное количество тёплых дней.
may_2017 = [24, 26, 15, 10, 15, 19, 10, 1, 4, 7, 7, 7, 12, 14, 17, 8, 9, 19, 21, 22, 11, 15, 19, 23, 15, 21, 16, 13, 25,
17, 19]
# Допи... |
print("Muhammad Osama 18b-003-cs CS-(A)")
print("Lab-08 28/12/2018")
print("Programming Exercise: Q-3")
first = 'Muhammad'
last = 'Osama'
street = 'Main Street'
number = 123
city = 'Karachi'
state = 'Sindh'
zipcode = '78487'
print('{0} {1}\n{3} {2}\n{4} {5} {6}'.format(first,last,number,street,city... |
def scanner():
try:
file = open('inputfile.txt', 'r')
nextCharacter = file.read()
file.close()
return nextCharacter
except:
print("Error opening file")
scanner() |
import sys
import string
dict_words_counts = {}
file_to_count = open(sys.argv[1])
for line in file_to_count:
line_list = line.split()
for word in line_list:
word = string.strip(word, ",.?/;:\'\"[]{}-()&%$#!`")
word = word.lower()
dict_words_counts[word] = dict_words_counts.get(word, 0) + 1
unsorted_list = ... |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
"""
... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def depth(self, root, d):
if root is None:
return d
if root.left and root.right:
... |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def count(self, l):
counta = 0
while l != None:
counta +=1
l = l.next
return counta
def add(self, l1, l2... |
class Node:
def __init__(self,data):
self.data = data
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self, newData):
self.data=newData
def setNext(self, item):
self.next = item
class Unordered... |
#condicion=True
#while condicion:
# print("ejecutando cicclo while")
#else:
# print ("Fin ciclo while")
i=0
while i<3:
print(i)
i+=1
else:
print("Fin ciclo while") |
condicion = False
if condicion == True:
print("la condicion es verdadera")
elif condicion == False:
print ("la condicion es falsa")
else:
print("condicion no reconocida ")
numero=int(input("Proporciones un numero entre 1 y 3"))
if numero == 1:
numeroTexto= "numero uno"
elif numero == 2:
numeroTexto=... |
# import statements
from bs4 import BeautifulSoup, Comment
import requests
import lxml
import re
from googlesearch import search
# global vars
titles = []
url_names = ['https://www.mckinsey.com/featured-insights/artificial-intelligence/notes-from-the-ai-frontier-modeling-the-impact-of-ai-on-the-world-economy']
url_sou... |
"""Turing machine that accepts set of all strings of balanced parentheses consisting of (, {, } and )"""
from machines import TuringMachine
def main():
machine = TuringMachine(states={"q0", "q1", "q2", "q3", "q4"},
symbols={"(", ")", "{", "}", "B", "X"},
bl... |
# You have deposited a specific amount of dollars into your bank account.
# Each year your balance increases at the same growth rate.
# Find out how long it would take for your balance
# to pass a specific threshold with the assumption
# that you don't make any additional deposits.
#
# Example
#
# For deposit = 10... |
# Consider integer numbers from 0 to n - 1
# written down along the circle in such a way that the distance
# between any two neighbouring numbers is equal (note that 0 and n - 1 are neighbouring, too).
#
# Given n and firstNumber, find the number which is written in the radially
# opposite position to firstNumber.
# ... |
# You are given an array of integers.
# On each move you are allowed to increase exactly one of its element by one.
# Find the minimal number of moves required to obtain a strictly
# increasing sequence from the input.
#
# Example
#
# For inputArray = [1, 1, 1], the output should be
# arrayChange(inputArray) = 3.
... |
# ask user to select menu
select_menu = eval(input("1. Binary to Decimal\n2. Decimal to Binary\n3. Octal to Decimal\n4. Decimal to Octal\n\
5. Octal to Binary\n6. Binary to Octal\n7. Decimal to Hexadecimal\n8. Hexadecimal to Decimal\n\
9. Hexadecimal to Binary\n10. Binary to Hexadecimal\nPlease select a menu: "))
... |
"""
@Date: 14/04/2021 ~ Version: 1.1
@Group: RIDDLER
@Author: Ahmet Feyzi Halaç
@Author: Aybars Altınışık
@Author: Ege Şahin
@Author: Göktuğ Gürbüztürk
@Author: Zeynep Cankara
@Description: A rule based Zookeeper System from Winston chapter 7
- Contains classes Zookeeper, Rule
- Zookeeper ... |
def moving_average(list_value, windows_size):
average_values = []
while(len(list_value) > windows_size):
sum = 0
index = 0
while(index < windows_size):
sum += list_value[index]
index += 1
average_values.append(sum / windows_size)
list_va... |
#!/usr/bin/env python
import time
def display_digit(number):
for i in range(0, number):
display = '.'
print(display, sep='', end='', flush=True)
time.sleep(1)
print(" [x] Done !")
return number
|
import sqlite3 as sql
class Quote:
"""
this class defines a quote type
"""
def __init__(self, text,movie_name,movie_id,quote_id,interested,total_replies):
self.text = text
self.movie_name = movie_name
self.movie_id = movie_id
self.quote_id = quote_id
... |
"""
This is a search command for doing ping lookups on results.
"""
import logging
from network_tools_app import ping
from network_tools_app.custom_lookup import CustomLookup
class PingLookup(CustomLookup):
"""
This class implements the functionality necessary to make a custom search command.
"""
de... |
import math
import os
import random
import re
import sys
def solve(m, t1, t2):
print(int(round(m+(m*t1/100)+(m*t2/100))))
if __name__ == '__main__':
meal_cost = float(input())
tip_percent = int(input())
tax_percent = int(input())
solve(meal_cost, tip_percent, tax_percent)
|
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
str = str.strip()
if not str:
return 0
if not (str[0].isdigit() or str[0] == '-' or str[0] == '+'):
return 0
new_str = []
if str[0] == '... |
def fibonachi(x):
f1 = f2 = fs = 1
print(f1)
print(f2)
m = 0
t = True
while t is not False :
fs = f1 + f2
f1 = f2
f2 = fs
if fs > x :
t = False
else:
print(fs)
t = True
return f2
def fibonachi2(n)... |
def sort(lst):
n = len(lst)
for i in range(n):
#Выбираем ключ , то что будем перемещать
k = lst[i]
# Место для перемещения
j = i
# Пока ключ меньше предыдущих элементов или пока массив не закончится передвигаем
while (lst[j-1] > k) and (j > 0):
... |
from csv import reader
import requests
def getrss(url, filename):
url = url
r = requests.get(url, allow_redirects=True)
open(filename, 'wb').write(r.content)
# skip first line i.e. read header first and then iterate over each row od csv as a list
with open('feeds.csv', 'r') as read_obj:
csv_reader = ... |
import datetime as dt
DATE_FORMAT = '%d.%m.%Y'
class Calculator:
def __init__(self, limit):
self.limit = limit
self.records = []
def add_record(self, record):
self.records.append(record)
def get_today_stats(self):
today_date = dt.date.today()
return sum(
... |
"""
Functions for finding a mask on a lat/lon grid from an input boundary
=====================================================================
"""
import warnings
import numpy as np
import shapely as sh
import matplotlib.path as mplp
import geocontour.grid as gcg
import geocontour.maskutil as gcmu
def center(latitude... |
var_1 = int(input("Введите первое число a: "))
var_2 = int(input("Введите второе число b: "))
var_3 = int(input("Введите третье число c: "))
res = var_1 and var_2 and var_3 and 'Нет нулевых значений.'
print(res)
res = var_1 or var_2 or var_3 or 'Введены все нули.'
print(res)
if var_1 > (var_2 + var_3):
print(f'раз... |
# multiAgents.py
# --------------
# Licensing Information: Please do not distribute or publish solutions to this
# project. You are free to use and extend these projects for educational
# purposes. The Pacman AI projects were developed at UC Berkeley, primarily by
# John DeNero (denero@cs.berkeley.edu) and Dan Klein (k... |
"""Custom topology example
Two directly connected switches plus a host for each switch:
host --- switch --- switch --- host
Adding the 'topos' dict with a key/value pair to generate our newly defined
topology enables one to pass in '--topo=mytopo' from the command line.
"""
from mininet.topo import Topo
class M... |
#UNIT CONVERTER
#1km is 0.621371192 miles
while True:
print("Hello, we are about to convert kilometers into miles!")
km = float(input("Tell me the number in kilometers: "))
mile = 0.621371192
print("it is " + format(km * mile) + " miles")
another = input("Do you want to do another conversion? ")
... |
import random
country_capitals = {"Greece": "Athens", "Serbia": "Belgrade", "Germany": "Berlin", "Switzerland": "Bern",
"Slovakia": "Bratislava", "Belgium": "Brussels", "Romania": "Bucharest", "Hungary": "Budapest", "Moldova": "Chisinau",
"Denmark": "Copenhagen", "Ireland": "Dublin", "Finland": "Helsinki", "Ukraine": ... |
# FIZZBUZ
print(" Let's play a game of fizzbuzz")
num1 = int(input("Choose a number between 1-100: "))
for num1 in range(1, num1 + 1):
if num1 % 3 == 0:
print("fizz")
elif num1 % 3 and num1 % 5 == 0:
print("fizzbuzz")
elif num1 % 5 == 0:
print("buzz")
else:
print(num1) |
import json
import tkinter as tkinter
from tkinter import filedialog
from datetime import date
# Sets the month and year variable based on the current date
month = date.today().month
year = date.today().year
# Create function to output the month and year
def printMonthYear(month, year):
# Create table for th... |
"""Utility functions for multiprocessing cpu intensive map functions.
Example
-------
>>> from moonshot.utils import multiprocess as mp
>>> shared_arg_list = ("hello world", [1, 2], np.array([2, 1]))
>>> def func(x):
... return "{}! {} + {} * {} = {}".format(
... mp.SHARED_ARGS[0], mp.SHARED_ARGS[1], mp.SH... |
#!/bin/python3
import math
import os
import random
import re
import sys
def binary_search(arr,V):
s = 0
e = len(arr)-1
while(s<=e):
mid = (s+e)//2
if arr[mid] < V:
s = mid + 1
elif arr[mid] > V:
e = mid - 1
else:
return mid
... |
import os
def diagonalDifference(arr):
m = len(arr)
sum_1 = 0
sum_2 = 0
for i in range(m):
sum_1 += arr[i][i]
sum_2 += arr[n-i-1][i]
return abs(sum_1-sum_2)
# Write your code here
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], ... |
class Student:
def __int__(self,name,rollno,marks):
print('Creating instance variables and performing initialization...')
self.name=name
self.rollno=rollno
self.marks=marks
s1=Student('Ram',101,90)
s2=Student('Sita',102,95)
print(s1.name.s1.rollno,s1.marks)
print(s2.name.s2.rollno,s2.marks)
|
l=[1,2,3,4,5]
def squareIt(n):
return n*n
l1=list(map(squareIt,l))
print(l1) |
d={100:'A',200:'B ',300:'C',400:'D'}
value=input('Enter value to find key:')
available=False
for k,v in d.items():
if v==value:
print('The corresponding key',k)
available=True
if available==False:
print('The specified value not found in dict')
|
def fact(n):
print('Executing Factorial Function with n value:',n)
if n==0:
result=1
else:
result=n*fact(n-1)
print('Returning Result of fact({}) is {}'.format(n,result))
return result
print(fact(3))
|
a=888
b=999
def add(x,y) :
print('performing add operation...')
print('The sum:' ,x+y)
def product(x,y) :
print('performing multiplication operation...')
print('The product:' ,x*y)
|
mail=input('Enter your mail id:')
try:
i=mail.index('@')
print('mail id contains @ symbol, which is mandatory')
except ValueError:
print('mail id does not contain @ symbol') |
from abc import abstractmethod,ABC
class Vehicle(ABC):
@abstractmethod
def getNoofWheels(self):pass
class Bus(Vehicle):
def getNoofWheels(self):
return 6
class Auto(Vehicle):
def getNoofWheels(self):
return 3
b=Bus()
print(b.getNoofWheels())
a=Auto()
print(a.getNoofWheels())... |
class P:
def m1(self):
print('Parent Method')
class C1(P):
def m2(self):
print('Child1 Method')
class C2(P):
def m3(self):
print('Child2 Method')
c1=C1()
c1.m1()
c1.m2()
c2=C2()
c2.m1()
c2.m3() |
class Solution(object):
def validPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s) <= 2:
return True
return self.isPalindrome(s)
def isPalindrome(self, s, can_recure=True):
left = 0
right = len(s) - 1
while left ... |
#!/usr/bin/python
"""
This script serves as the entry point for a simple sorting program
"""
import argparse
import sys
from algorithms import sort_fns
from algorithms import url_validation_fns
def main():
parser = argparse.ArgumentParser(description='Simple sort program')
parser.add_argument('-i', metavar='in-... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.