text stringlengths 5 121k |
|---|
from typing import List
def mergeTwoLists(l1: List[int], l2: List[int]) -> List[int]:
return sorted(l1 + l2)
if __name__ == "__main__":
list1 = [int(x) for x in input().split()]
list2 = [int(x) for x in input().split()]
print(mergeTwoLists(list1, list2))
|
from math import ceil, sqrt
for _ in range(int(input())):
a, b = (int(x) for x in input().split())
i = ceil(sqrt(a))
cnt = 0
while i <= sqrt(b):
i += 1
cnt += 1
print(cnt)
|
def arrayUpdate(nums: list, target: int) -> int:
if nums[0] >= target:
return 0
return target - min(nums)
if __name__ == "__main__":
res = list()
array_len, tar = (int(x) for x in input().split())
for _ in range(int(input())):
res.append(arrayUpdate([int(x) for x in input().split()]... |
def lengthOfLongestSubstring(s: str) -> int:
left = length = 0
visited = dict()
for pos, char in enumerate(s):
if char in visited and visited[char] >= left:
left = visited[char] + 1
else:
length = max(length, pos - left + 1)
visited[char] = pos
retur... |
from collections import namedtuple
''' Simplified Solution '''
total_students, Student = int(input()), namedtuple('Student', list(str(input()).split('\t')))
print('{:.2f}'.format(sum([int(Student(*input().split()).MARKS) for _ in range(total_students)]) / total_students))
''' Descriptive Solution '''
|
import unittest
def is_divide_by(number, a, b):
return (number % a) == 0 and (number % b) == 0
class is_divide_by_Test(unittest.TestCase):
def test_case1(self):
self.assertEqual(is_divide_by(-12, 2, -6), True)
def test_case2(self):
self.assertEqual(is_divide_by(-12, 2, -5), False)
def... |
'''
Your job is to change the string s using a non-negative integer n.
Each bit in n will specify whether or not to swap the case for each
alphabetic character in s. When you get to the last bit of n, circle
back to the first bit. If the bit is 1, swap the case. If its 0, don't swap the case.
You should skip the ch... |
import unittest
from typing import List
from collections import defaultdict
def minimumDistances(arr: List[int], size: int) -> int:
minDist = 10**5
position_map = dict()
position_map = defaultdict(list)
for pos, item in enumerate(arr):
position_map[item].append(pos)
for i in position_map:... |
import pyfiglet
import random
number = random.randint(0,100)
no_of_guesses = 0
banner = pyfiglet.figlet_format("Guess The Number")
print(banner)
print("Game by 2kwattz \nTries Left:10")
while (no_of_guesses<10):
no_of_guesses = no_of_guesses + 1
guess = int(input("Enter the number\n"))
i... |
n = int(("Input your positive integer: "))
n = 2 * n
n_fact = 1
for i in range(1, n):
n_fact = n_fact + n_fact*i
print(n_fact) |
import hashlib
import random
import string
import os
class Utility:
'''
Provides useful general functions--such as generating a random string--of which
can be useful to multiple programs in the application.
'''
def genRandomString(size=10, chars=string.ascii_letters + string.digits):
'''... |
import matplotlib.pyplot as plt
from math import pi
ted_abilities = {
'COMPUTER': 62,
'ENGLISH': 55,
'LONGBOARD': 40,
'UKULELE': 35,
'DRIVING': 50,
}
categories = ted_abilities.keys()
N = len(categories)
values=list(ted_abilities.values())
values += values[:1]
angles = [n / float(N) * 2 * p... |
def yell(text):
return text.upper() + '!'
print(yell('hello'))
bark = yell
print(bark('woof'))
print(bark.__name__)
funcs = [bark, str.lower, str.capitalize]
print(funcs)
for f in funcs:
print(f, f("hi there"))
print(funcs[0]("yo man"))
def greet(func):
greeting = func("Hi, I'm Python")
... |
import pandas as pd
df = pd.read_csv("weather_data_1.csv")
print(df)
df=pd.read_excel("weather_data_1.xlsx","Sheet1")
print(df)
weather_data = {
'day': ['1/1/2017','1/2/2017','1/3/2017'],
'temperature': [32,35,28],
'windspeed': [6,7,2],
'event': ['Rain', 'Sunny', 'Snow']
}
df = pd.Data... |
myList = ["a", "b", "c", "d"]
letters = "abcdefghijklmnopqrstuvwxyz"
numbers = "123456789"
newString = " Mississippi ".join(numbers)
print(newString)
fruit = {
"Orange":"Orange juicy citrus fruit",
"Apple":"Red juicy friend",
"Lemon":"Sour citrus fruit",
"Lime":"Green sour fruit"
}
veggies =... |
import time
from turtle import *
from shapes import *
tommy = Turtle()
tommy.shape("turtle")
tommy.speed(10)
draw_circle(tommy, "green", 50, 0, 100)
draw_circle(tommy, "green", 50, 0, 200)
draw_circle(tommy, "blue", 50, 75, 25)
draw_circle(tommy, "red", 50, -75, 25)
draw_square(tommy, "green", 50, -50, -200)
... |
def getCreds():
username = input("What's your username? ")
password = input("what's your password?")
return {"username": username, "password": password}
user_info = [
{
"username": username,
"password": password
},
{
"username": username,... |
name = str(input("Please enter your name: "))
age = input("How old are you {0} ".format(name))
print(age)
print() |
low = 1
high = 1000
print("Please think of a number between {} and {}".format(low, high))
input("Press ENTER to start")
guesses = 1
while low != high:
print("\tGuessing in the range of {} and {}".format(low, high))
guess = low + (high - low) // 2
high_low = input("My guess is {}. Should I guess High... |
class Gamers:
def __init__(self, players, playerCount):
self._players = players
self._playerCount = playerCount
def __playerInfo__(self):
return "There are " + self.playerCount + " players, they are:\n" + self.players
def __players__(self, count):
self._playerCount = (i... |
from PIL import Image
def open_image():
im = Image.open(r"C:\Users\dks10\OneDrive\Desktop\Projects\Code\Python\PythonCrypto\Module_3\eye.png")
file = open('C:\\Users\\dks10\\OneDrive\\Desktop\\Projects\\Code\\Python\\PythonCrypto\\Module_3\\eye.png', 'rb')
open_f = file.read()
print(... |
class Person():
def __init__(self,name,DOB,height,weight):
self.name = name
self.DOB = DOB
self.height = height
self.weight = weight
Darius = Person("Darius", "10/18/1995","6 foot", 185)
print(Darius.name)
print(Darius.DOB)
print(Darius.weight)
print(Darius.height)
... |
Number1 = input("Enter your first number: ")
Number2 = input("Enter your second number: ")
NumberAsk = input("Would you like to add a third number? Y or N: ")
if NumberAsk == str("Y"):
Number3 = input("Please enter your third number: ")
Operation = input("What operation would you like to perform on these numbers? ... |
import csv
def is_anagram(str1, str2):
return sorted(list(str1)) == sorted(list(str2))
file = open("input.txt", "r", encoding="utf-8")
count = int(file.readline())
prepared_words = (([w.lower().strip() for w in file.readlines()]))
total = []
added = []
for i in range((len(prepared_words) - 1)):
if i in adde... |
import re
file = open("input.txt", "r", encoding="utf-8")
output = open("output.txt", "w", encoding="utf-8")
count = int(file.readline())
regex = re.compile('[^а-я]')
for i in range(count):
s = file.readline()
s = s.lower()
s = s.replace('ё', 'е')
s = regex.sub('', s)
if s == s[::-1]:
... |
menu='''
MENU
====
1- Somar.
2- Subtrair.
3- Multiplicar.
4- Dividir.
Escolha:
'''
def leiaInt(msg):
ok = False
valor = 0
while True:
soma_x = 0
soma_y = 0
subtrair_x = 0
subtrair_y = 0
multiplicar_x = 0
multiplicar_y = 0
... |
import urllib.request
import json
class Solution:
def run(self, teamKey):
goals = 0
def get_json(url):
with urllib.request.urlopen(url) as data:
data = data.read()
return json.loads(data.decode())
json_string = get_json("https://raw.githubusercontent.com/openfootball/football.json/m... |
def tower(n,source,helper,dest):
if n == 1:
print("move disk",n, "from", source,"to",dest)
return
else:
tower(n-1,source,dest,helper)
print("move disk",n,"from",source,"to", dest)
tower(n-1,helper,source,dest)
tower(5,"a","b","c")
|
from collections import defaultdict
def repeate(path):
dic = {}
sort_dic = {}
with open(path,"r") as f:
lines = f.read().splitlines()
for lin in range(0,len(lines)):
words = lines[lin].split()
for word in range(0,len(words)):
if words[word] in dic:
... |
def find_multipex(x, y):
z = 0
lst = []
if y < x:
print(lst)
return 0
else:
for i in range (1,y):
i = i * x
lst.insert(z, i)
z = z + 1
if i > y:
lst.pop()
print(lst)
return ... |
def sample():
"""
Loop through number range 1 though 11 and multiply by 2
"""
total = 0
for number in range(2, 101, 2):
if number == 4:
continue
total += number
product = number * 2
print(number, '* 2 = ', product)
... |
"""
Created on Fri Jan 18, 2019
File: Testing for a Substring with the in operator
@author: Byen23
Another problem involves picking out strings that contains known substrings. FOr example you might wnat to pick out filenames with a .txt extension. A slice would work for this but using Python's in operator is the... |
a = float(input())
b = float(input())
import math
test = a*b
print(math.sqrt(test)) |
def findLine(prog, target):
for i in range(len(prog)):
splited=prog[i].split()
if splited[0]==str(target):
return i
def execute(prog):
location = 0
i=10
visited=[False]*len(prog)
for i in range(len(prog)):
if location==len(prog)-1: return "success"
temp=(prog[location].split())... |
def lowerChar(char):
if ord(char) >= ord('A') and ord(char) <= ord('Z'):
char = chr(ord(char)+32)
return char
else:
return char
|
def convert_to_string(string):
return str(string)
a = []
b = []
def two_lists(a,b):
if a == b:
return a, b
else:
print("Go to hell")
def pancakes(mylist):
mylist[0] = "pancakes"
return mylist
pancakes([1,2,3])
|
"""this module will deal with the parts of github urls"""
class Elem(object):
"""Class that provides utility for github urls"""
def __init__(self, url):
self.url = url
def is_blob(self):
"""returns true if this elem is a file and false if it is a folder"""
parts = self.url.split('... |
print("Program that adds two numbers to each other")
a = int(input("First number: "))
b = int(input("Second number: "))
print("Sum of a =", a, "+", "b =", b, "is equal to", a + b)
|
names = ["Arkadiusz", "Claire", "Peter", "Jacob"]
numbers = [3, 12, 24, 7, -8]
if ("John" not in names):
print("Hello John, welcome!")
if (4 in numbers):
print("Number 4 is inside the list called numbers")
else:
print("Number 4 is not inside the list")
|
"""
FILE - name of location that stores pernamently data
RAM - temporary data storage
Operations you can do on a file:
1) opening
2) writing/reading
3) closing
basic modes(ways) of opening files:
r - R ead - default
w - W rite - if the file existed (will be removed), if not will be created
a - A ppend (adding new ... |
"""
Measuring the performance of code
"""
import time
def sum_up_to(end):
sum = 0
for number in range(1, end+1):
sum = sum + number
return sum
def sum_up_to2(end):
return sum([number for number in range(1, end+1)])
def sum_up_to3(end):
return sum({number for number in range(1, end+1)})... |
''' file name : filter2d.py
Description : This sample shows how to filter/convolve an image with a kernel
This is Python version of this tutorial : http://opencv.itseez.com/doc/tutorials/core/mat-mask-operations/mat-mask-operations.html#the-filter2d-function
Level : Beginner
Benefits : Learn to convolve with cv2.fi... |
''' file name : remap.py
Description : This sample shows how to remap images
This is Python version of this tutorial : http://opencv.itseez.com/doc/tutorials/imgproc/imgtrans/remap/remap.html#remap
Level : Beginner
Benefits : Learn to use remap function
Usage : python remap.py
Written by : Abid K. (abidrahman2@g... |
import os
class Programme():
def __init__(self):
try:
self.fichier_python = open("fichiers/fichier_python.py", "w")
except:
quit()
self.content = ""
self.avant = "\t"
self.ligne = ""
self.fin_ligne = ""
self.nombre_indentation = [1]
... |
def merge(arrA, arrB):
elements = len(arrA) + len(arrB)
merged_arr = [None] * elements
while None in merged_arr:
if not arrA:
popped = arrB.pop(0)
first_instance = merged_arr.index(None)
merged_arr[first_instance] = popped
elif not arrB:
... |
num=int(input("how many toffe u want"))
av=10
i=1
while i<=num:
if i<=av:
print("Plese collect toffee=",i)
else:
print("out of stock")
break
i=i+1
else:
print("Thanks Please Visit again") |
string=input()
substring=input()
s=string.strip()
sb=substring.strip()
b=s.find(sb)
print(b)
c=s[b:3]
k=s.remove(c)
print(k)
|
class rectangle:
def __init__(self,l,b,r):
self.length=l
self.bredth=b
self.radius=r
def area_rectangle(self):
a=self.length*self.bredth
print(a)
def area_circle(self):
p=self.radius*3.14
print(p)
a=int(input('enter the value of length'))
b=int(input('... |
"""
字符串排序
1. 题目
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
2. 思路
(1)递归: 分解成子问题求解
* 如果len(s)==1:
输出
* 否则,分解为s[i], s[0:i]+s[i+1:n]
"""
class Solution:
def Permutation(self, ss):
if ss is None:
return None
res=[]
... |
import DoublyLinkedList
import Vector
class MergeSort(object):
def listMergeSort(self, list, p, n):
"sort n elements at the beginning of node p"
if n < 2:
return p
mid = n / 2
q = list.getNodeAfterNIndex(p, mid)
p = self.listMergeSort(list, p, mid... |
import BinTree
import Utils
def randomBinTree(bt, x, h):
if h <= 0:
return
if Utils.randomRange(h):
randomBinTree(bt, bt.insertAsRC(x, Utils.randomRange(100)), h - 1)
if Utils.randomRange(h):
randomBinTree(bt, bt.insertAsLC(x, Utils.randomRange(100)), h - 1)
def randomBi... |
import sys
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
... |
import csv
import numpy as np
from pathlib import Path
class Feature_selection:
'''This class is used to select only some features
of the samples written in a csv file.
'''
EXTENTION = '.csv'
TITANIC_FEATURES = ['id', 'pclass', 'survived',
'name', 'sex', 'age', 'sibsp',
'parch', 'ticket', 'fare',
'... |
import addition
import subtraction
import multiplication
import division
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
UserChoice = input("Choose (1,2,3,4): ")
if UserChoice in ('1', '2', '3', '4'):
num1 = float(input("Ent... |
def factorialFunc(n: int)->int:
if n<=0:
return 0
if n==1:
return 1
return n * factorialFunc(n-1)
|
from tkinter import *
from tkinter import messagebox
def closeWindow():
messagebox.showinfo(title="警告",message = "不许关闭,好好回答")
return
def closeAllWindow():
window.destroy()
def Love():
love = Toplevel(window)
love.geometry("300x100+610+260")
love.title("好巧,我也是")
label = Label(lov... |
def find_index(numbers, low, high):
if low >= high:
return None
mid = (low + high) // 2
if numbers[mid] == mid:
return mid
if numbers[mid] < mid:
return find_index(numbers, mid + 1, high)
return find_index(numbers, low, mid)
def main():
assert find_index([-5, 1, 3, 4, 5... |
"""
Proof: http://mathforum.org/library/drmath/view/55956.html
This problem is clearly a recursive problem:
- To move n disks from one pole to another, we must first move n-1 disks to the
helper pole and then move the n'th disk to the target pole. Finally, move the
n-1 disks from the helper pole to the tar... |
def pascals(n):
triangle = [[1] * i for i in range(1, n + 1)]
for i in range(n):
for j in range(1, i):
triangle[i][j] = triangle[i-1][j]+triangle[i-1][j-1]
return triangle[-1]
def main():
assert pascals(6) == [1,5,10,10,5,1]
if __name__ == '__main__':
main()
|
class Node(object):
def __init__(self, value):
self.value = value
self.children = []
def is_symmetrical(root):
return find_symmetry(root, root)
def find_symmetry(root1, root2):
if not (root1 or root2):
return True
if not (root1 and root2):
return False
if root1.va... |
def is_valid(string):
for sub in string.split("."):
if len(sub) > 3 or int(sub) < 0 or int(sub) > 255:
return False
if len(sub) > 1 and int(sub) == 0:
return False
if len(sub) > 1 and int(sub) != 0 and int(sub[0]) == 0:
return False
return True
def g... |
def calculate_angle(hour, minute):
minute_angle = 6 * minute
hour_angle = (30 * hour + (30 * (minute/60))) % 360
print(minute_angle, hour_angle)
return hour_angle - minute_angle if hour_angle >= minute_angle else minute_angle - hour_angle
def main():
assert calculate_angle(3, 30) == 75
ass... |
import heapq
def rearrange(string):
character_count = [(-string.count(char), char) for char in set(string)]
if any([-count for count, char in character_count]) > (len(string) + 1) / 2:
return ""
heapq.heapify(character_count)
result = ""
while len(character_count) >= 2:
count1, cha... |
from copy import copy
def find_permutations(numbers, low, high):
if low == high:
return [numbers]
result = []
for i in range(low, high+1):
temp = copy(numbers)
temp[low], temp[i] = temp[i], temp[low]
result.extend(find_permutations(temp, low + 1, high))
return result
... |
def string_compression(string):
count = 1
current_char = string[1]
result = []
for char in string[1:]:
if char == current_char:
count += 1
else:
if count > 1:
result.extend([current_char, str(count)])
else:
result.append... |
def count(parentheses):
p_stack = []
changes = 0
for p in parentheses:
if p == ")":
if not p_stack:
changes += 1
else:
p_stack.pop()
else:
p_stack.append(p)
if p_stack:
if len(p_stack) % 2:
changes +=... |
from collections import deque
def longest_substring_with_k_distinct_characters(string, k):
char_dict = dict()
current_sub_string = deque()
largest_substring = ""
for char in string:
current_sub_string.append(char)
try:
char_dict[char] += 1
except:
char_d... |
class Node(object):
def __init__(self, val):
self.val = val
self.next = None
self.prev = None
def is_palindrome(node):
if not (node and node.next):
return True
head = node
current = None
while node.next:
if not node.next.next:
current = node.next... |
from string import ascii_uppercase
def convert(number):
alphabet_dict = {number: ascii_uppercase[number - 1] for number in range(0, 26)}
result = ''
while number >= 1:
res = (number % 26)
result = alphabet_dict[res] + result
if res == 0:
number -= 1
number //= 2... |
def sum_binary(bin1, bin2):
carry = 0
result = ""
index = 0
bin1, bin2 = bin1[::-1], bin2[::-1]
while index < len(bin1) or index < len(bin2):
if index < len(bin1):
carry += ord(bin1[index]) - ord('0')
if index < len(bin2):
carry += ord(bin2[index]) - ord('0')
... |
from collections import deque
def eval(expression):
res = 0
remainingExp = deque()
currentExp = deque()
expression = expression.replace(" ", "")
for exp in expression:
if exp == ")":
for _ in range(len(currentExp)):
remainingExp.pop()
while currentEx... |
from collections import deque
def get_values(numbers):
temp = 1
result_array = [1 for _ in numbers]
for index, number in enumerate(numbers):
result_array[index] = temp
temp *= number
temp = 1
for index in range(len(numbers) - 1, -1, -1):
result_array[index] *... |
""" Test cases for nested lists file.
"""
import unittest
import nested_lists
class TestNestedLists(unittest.TestCase):
""" Test cases for nested list function.
"""
def test_remove_nested_loop_dict(self):
""" Test case for nested lists passing a dictionary.
"""
expected = {}
... |
from tkinter import *
d = {'thai':'th','japanese':'jp','korean':'kr','chinese':'cn'}
def on_select(e):
print(e.widget['text'], e.widget['value'])
root = Tk()
root.option_add('*Font','consolas 20')
tv_code = StringVar()
tv_code.set('thai')
n_col = 3
i=0
for k,v in d.items():
r = Radiobutton(root,text=k, value=... |
row, col = input().split()
numberSum, matrix = [], []
for _ in range(int(row)):
matrix.append([int(j) for j in input().split()])
for _ in range(int(row)):
numberSum.append([int(j) for j in input().split()])
for i in range(len(matrix)):
for j in range(int(col)):
print(matrix[i][j] + numberSum[i][j... |
num = [10,2,3.4,56,1,1,11]
num2 = [10,2,3.4,56,1,1,11]
num.sort()
print(num)
num2.sort(reverse=True)
print(num2)
list1 = ['aa','b','eeee','ccccc','ddd']
list1.sort(key=len)
print(list1)
list2 = [[2,9],[1,10],[3,7]]
list2.sort()
print(list2)
def SortBySec(element):
return element[1]
list2.sort(key=SortBySec)
p... |
fish_kg = []
number = []
while True:
x = int(input())
if x == 0:
max_min = input().lower()
if max_min == "max":
fish_kg.sort()
fish_kg.reverse()
for i in fish_kg:
a = str(i)
number.append(a)
if max_min == "min":
fish_kg.sort()
for i in fish_kg:... |
"""
Python 3.6 uses the input() method.
Python 2.7 uses the raw_input() method.
"""
username = input("Enter username:")
print("Username is: " + username)
username = raw_input("Enter username:")
print("Username is: " + username) |
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
newarr = np.array_split(arr, 3)
print(newarr)
newarr = np.hsplit(arr, 3)
print(newarr) |
def list_sum(data_list):
total = 0
for element in data_list:
if type(element) == type([]):
total = total + list_sum(element)
else:
total = total + element
return total
print(list_sum([2,4,[6,8],[10,12]])) |
import random
def add(a,b):
return a + b
def f(func,a,b):
return func(a,b)
def fx(func):
for _ in range(10):
a = random.randrange(1,13)
b = random.randrange(1,13)
print(f"{a} op {b} = {func(a,b)}")
def mental_math():
funcs = {
'+':lambda a,b: a+b,
'-':lambda a,... |
for var in "python":
print(var)
for letter in [10,20,30,40,50]:
if letter >= 25:
print(letter,'greater than 25')
else:
print(letter,'lass than 25') |
def demo1():
weight = [70,60,48]
height = [170,175,161]
bmi = []
for i in range(len(weight)):
bmi.append(weight[i] / (height[i]/100) ** 2)
return bmi
def demo2():
weight = [70,60,48]
height = [170,175,161]
bmi = []
for w,h in zip(weight,height):
bmi.append(w / (h ... |
from science import *
y=2
t=0
constant=10
dt=0.01
reset()
store(t,y)
for i in range(9000):
dy=constant*dt
y=y+dy
t=t+dt
if i%100 == 0 :
store(t,y)
t,y=recall()
plot(t,y)
xlabel('time')
ylabel('y')
x=2
v=1
t=0
k=10
c=0.1
dt=0.0005
... |
import os
import sys
from jk_console import *
t = SimpleTable()
with t.addRow("Key", "Value") as r:
r.color = Console.ForeGround.STD_LIGHTGREEN
r.case = SimpleTable.CASE_UPPER
r.hlineAfterRow = True
t.addRow("Country", "Germany")
t.addRow("State", "Berlin")
t.addRow("Area", "891.7 km2 ")
t.addRow("S... |
from jk_console import Console
print(Console.ForeGround.CYAN + "Hello World!" + Console.RESET)
print(Console.BackGround.rgb256(128, 0, 0) + "Hello World!" + Console.RESET)
|
def y(a):
return len(a)
a = ['Andilala', 'Budiman', 'Caca']
x = map(y, a)
a = ['Cokelat', 'Melon', 'Nangka']
b = ['Apel', 'Jeruk', 'Nanas']
def combi(a, b):
return a+' '+b
x = map(combi, a, b)
x = [2, 4, 6, 8, 10]
def pangkat2(a):
return a ** 2
y = map(lambda x : x ** 2, x)
x = pow(2, 2... |
import math
tt = int(input())
for _ in range(tt):
n, k = input().split(' ')
n = int(n)
k = int(k)
if (n % (k**2) == 0):
print("NO")
else:
print("YES")
|
x=int(input('enter the x: '))
y=int(input('enter the y: '))
def mySum(x,y):
print (x+y)
mySum(x,y)
|
import re
preg = input()
string = input()
result_string = ''
preg = preg.upper() + preg.lower()
if '+' in preg:
preg = preg+'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
if preg:
for char in string:
if char in preg:
continue
else:
result_string = result_string + char
pri... |
from norm import minimum
f_number_1 = {(0.3, 1), (1, 2)}
f_number_2 = {(1, 1), (0.5, 2)}
def addition(number_1, number_2, norm):
a_set = set()
for x in number_1:
for y in number_2:
fuzzy_sum = (norm(x, y)[0], x[1] + y[1])
print("x: {}, y: {}, fuzzy sum: {}".format(x, y, fuzz... |
import math
from functools import reduce
input = open('day1input.txt').read().splitlines()
def calcFuel(amt):
return math.floor(int(amt) / 3) - 2
def addFuel(f1, f2):
return f1 + f2;
def fuelRequired(modules):
return reduce(addFuel, map(calcFuel, modules))
def additionalFuelNeeded(fuel):
total = 0
... |
"""This class performs session table related database queries and common checks"""
__license__ = "GPLv3"
class SessionDB:
"""
This class performs database queries for session table.
:Example:
from lib.database_lib.session_db import SessionDB
from lib.database import Database
#... |
"""This class performs database queries for the physiological_annotation_file table"""
__license__ = "GPLv3"
class PhysiologicalAnnotationFile:
def __init__(self, db, verbose):
"""
Constructor method for the PhysiologicalAnnotationFile class.
:param db : Database class ... |
from sys import exit
from random import randint
from map import Map
from leaderboard import Leaderboard
from scores import Score
from game_engine import Engine
moves = 0
name = ''
leaderboard = Leaderboard()
def game_over(won):
global name
global moves
score = Score(name, moves)
if won:
le... |
def main():
centimeters = eval(input("How many centimeters?"))
inches = centimeters/2.54
print("you have", inches, "inches.")
main() |
import webbrowser
sites = [ 'site1', 'site2', 'site3', 'etc.' ]
print('Multiple google search on sites:')
for site in sites:
print(site)
keyword = input('\nKeyword: ')
for site in sites:
webbrowser.open_new_tab('http://www.google.com/search?btnG=1&q=%s' % keyword + ' ' + site)
|
from threading import Thread
global i
i = 0
def someThreadFunction1():
global i
for s in range(0,1000000):
i = i+1
def someThreadFunction2():
global i
for s in range(0,1000000):
i = i-1
def main():
someThread1 = Thread(target = someThreadFunction1, args = (),)
someThread2 = Thread(target = someThreadFuncti... |
import socket
target=input("enter the ipaddress: ")
port_rg=input("enter the port range: ")
low=int(port_rg.split('-')[0])
high=int(port_rg.split('-')[1])
print('########################################################################')
print('target ip:',target,'scanning start from:',low,' scanning end at... |
class Movie():
"""This class defines a movie.
Attributes:
movie_title (str): The title of the movie
poster_url (str): The url to the movie poster
youtube_link (str): The link to the movie trailer
"""
def __init__(self, movie_title, poster_url, youtube_link):
self.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.