text
stringlengths
5
121k
class Node: def __init__(self, data): self.data = data self.next = self class LinkedList: def __init__(self): self.head = None def printlist(self): temp=list.head while(temp.next!=list.head): print(temp.data) temp=temp.next ...
time = input() time = time.split(" ") hour = int(time[0]) minutes = int(time[1]) if minutes < 45: minutes = 60 - abs(minutes - 45) hour -= 1 else: minutes = minutes - 45 if hour < 0: hour = 24 + hour print(hour,minutes)
from _datetime import date import calendar testInput = input() testInput = testInput.split() day = int(testInput[0]) month = int(testInput[1]) myDate = date(2009,month,day) print(calendar.day_name[myDate.weekday()])
def solution(numbers): answer = [] total=[] n=len(numbers) for i in range(0,n): for j in range (i+1,n): k=numbers[i]+numbers[j] if k not in total: total.append(k) total.sort() return total print(solution([2,1,3,4,1])) print(s...
import matplotlib.pyplot as plt def logistic_a(x0, R, m): """ First part returns the current state of the system, xn as a function of time, n """ cur_state = x0 xn = [cur_state] n = range(0,m+1) for i in n[1::]: next_state = cur_state * R * (1 - cur_state) xn.appe...
weight = int(input("enter your weight: ")) print(f'''your weight is {weight} is it in pound or kilos ?''') unit = input("(l)pound or (k)kilogram: ") if unit.upper() == "L": convert = weight * 0.45 print(f"you are {convert} kilos") else: convert = weight / 0.45 print(f"you are {convert} pound")
from linkedlist import LinkedList from linkedlist import Node class Queue(LinkedList): def __init__(self, iterable=None): super().__init__(iterable) def enqueue(self, item): """Add an object to the end of the Queue.""" self.append(item) def dequeue(self): """Remove and ret...
from typing import List def find_product(inputs: List[int]) -> int: """Given a list of integers, if the sum of two element is 2020, return it's product.""" needs = {2020 - x for x in inputs} for num in inputs: if num in needs: ans = num * (2020-num) return...
from cs50 import get_float user_money = 0 while (user_money <= 0): user_money = get_float("Change owned: ") u = user_money * 100 num_coins = u//25 + (u % 25)//10 + ((u % 25) % 10)//5 + ((u % 25) % 10) % 5 print(int(num_coins))
class Solution: def findComplement(self, num: int) -> int: if num == 0: number= self.bit_complement(num) else: remiders = list() while num >= 1: reminder = num % 2 num = num // 2 remiders.append(self.bit_compleme...
__author__ = "saimadhu.polamuri" import math class Solution: def majorityElement(self, nums) -> int: array_len = len(nums) if array_len > 0: majority_element = nums[0] majority_element_frequency = 1 if array_len > 1: hash_map = dict() ...
__author__ = "saimadhu.polamuri" class Solution: def frequencySort(self, s): frequency_dict = {} for element in s: if element in frequency_dict: frequency_dict[element] += 1 else: frequency_dict[element] = 1 sorted...
def main(): with open('input', 'r') as file: answers = [line.rstrip() for line in file] answers.append('') group = "" count = 0 for ans in answers: if (ans == ''): count += len(set(group)) group = "" else: group += ans pr...
def fib(n): assert n >= 0 and int(n) == n, "n must be a positive integer" if n == 1: return 0 elif n == 2: return 1 else: return fib(n-1) + fib(n-2) print("The 4th fibonacci number is: ", fib(4)) print("The 10th fibonacci number is: ", fib(10)) def sum_digits(n): ...
""" @file 키패드누르기v2.py @brief 2020 카카오 인턴십 1번 @desc 구현 두 번째 풀이 - 키패드 위치를 자료구조로 저장 (리스트, 딕셔너리) - 키패드 위치 """ numbers = [1, 3, 4, 5, 8, 2, 1, 4, 5, 9, 5] hand = "right" def solution(numbers, hand): answer = '' position = [[1, 3], [0, 0], [1, 0], [2, 0], [0, 1], [1, 1],...
""" @file K번째수.py @brief 정렬 - Level 1 @desc """ def solution(array, commands): answer = [] for i in commands: arr = sorted(array[i[0]-1:i[1]]) answer.append(arr[i[2]-1]) return answer
import numpy as np import tensorflow as tf import matplotlib.pyplot as plt np.random.seed(101) tf.set_random_seed(101) x_data = np.linspace(0, 10, 10) + np.random.uniform(-1.5, 1.5, 10) print(x_data) y_label = np.linspace(0, 10, 10) + np.random.uniform(-1.5, 1.5, 10) plt.plot(x_data, y_label, '*') np.r...
import numpy def add(): num1=int(input("enter number 1:")) num2 = int(input("enter number 2:")) return num1+num2; def sub(): num1 = int(input("enter number 1:")) num2 = int(input("enter number 2:")) return num1-num2; def multi(): num1 = int(input("enter number 1:")) num...
import sys def choose_evens(input_string): evens = [int(element) for element in input_string.split(',') if(int(element)> 0 and int(element) % 2 == 0) ] all_numbers = [int(element) for element in input_string.split(',') if int(element)> 0] even_number_rate = sum(evens) / sum(all_numbers) print("Ev...
import random from itertools import combinations def getExactChangeNum(d): changes = [] for i in range(239): changes.append(i) for j in range(239): if (j == d[0] - 1 or j == d[1] -1 or j == d[2] - 1 or j == d[3] - 1 ): changes[j] = 1 conti...
import random rand_num=random.randint(1,3) if rand_num==1: com_side="rock" elif rand_num==2: com_side="paper" else: com_side="scissors" i=0 while i<5: print("You can input 'stop' at anytime to stop the game but nothing else is allowed.") user_side=input("Please input your choice (R P S stands for r...
from sys import argv script, filename = argv[0], argv[1] print(f"args: {argv}") txt = open(filename) print(f'file named "{filename}" contents:') print(txt.read()) print(f'file named "{filename}" contents by line by line in list:') txt = open(filename) print(txt.readlines()) print("type the filename to read again:"...
with open('hello_foo.txt', 'w') as f: f.write('hello, world!') with open('hello_foo.txt', 'r') as f: print(f.read()) print() from contextlib import contextmanager import os @contextmanager def working_directory(path): current_dir = os.getcwd() os.chdir(pa...
print( {True: 'yes', 1: 'no', 1.0: 'maybe'} ) print(True == 1 == 1.0 ) print( (hash(True), hash(1), hash(1.0)) ) d = {} print(d) str = 'myKey' str2 = 'myKey2' d[str]=1 d[str2]=5 d[str]+=2 d['another'] = 'string of *&^%' d['myKey5']=0 print(d) e =d.pop('another') print(e) print(d) d2 = {'wow'...
from enviroment import next_move import random from PriorityQueue import PriorityQueue if __name__ == '__main__': myQueue = PriorityQueue() start = list(range(0,9)) random.shuffle(start) start2 = list(range(0,9)) random.shuffle(start2) print("start+>",start) myQueue.insert(start,12) ...
import sys from random import randint def display_menu(): menu_items = [ "[ 1 ] Generate 3-digit lottery number", "[ 2 ] Generate 4-digit lottery number", "[ x ] Quit (Exit application)" ] print("Please select an option from the following menu:\n") for item in menu_items: ...
def solution(phone_book): answer = True dict={} phone_book.sort() before='a' for p in phone_book: if before in p: return False before=p return answer
from math import pi print("Day 2: 30 days of python") firstName = "ivan" lastName = "Rosario" fullName = firstName + " " + lastName country = "US" city = "miami" age = "21" year = "2020" is_married = False is_true = True is_light_on = False i, j = 0, 3 print(type(firstName)) print(type(lastName)) print(type(fullName...
import string multiplier_list = [1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 21, 22, 23, 24, 26, 27, 28, 29, 31, 32, 33, 34, 36, 37, 39] def affine_cipher(): multiplier = 13 offset = 7 with open("task2_encrypted_message.txt", "r") as input_message: encrypted_message = input_mes...
l = [42, '42', 'quarante-deux', 42.0, True, [42], {42:42}, (42,), set()] def my_var(): for i in l: print(str(i) + ' est de type ' + str(type(i))) if __name__ == '__main__': my_var()
from PyPDF2 import PdfFileReader, PdfFileWriter def split_single_pdf(read_file, start_page, end_page, pdf_file): fp_read_file = open(read_file, 'rb') pdf_input = PdfFileReader(fp_read_file) pdf_output = PdfFileWriter() for i in range(start_page, end_page): pdf_output.addPag...
class Aircraft: """ a class to store Airport objects """ def __init__(self, code, units, range): """ class constructor initialises variables with input """ self.code = code self.units = units self.range = range def get_range(self): """ method to retrieve aircraft ...
import sys m, n = [int(x) for x in raw_input().split(" ")] evenValues = [] for i in range(m+1, n): if (i & 1) == 0: evenValues.append(str(i)) print(' '.join(evenValues))
def fibo(n): if n < 2: return 1 if memo[n] != 0: return memo[n] memo[n] = fibo(n-2) + fibo(n-1) return memo[n] n = int(raw_input()) memo = [0 for i in range(n)] memo[0] = memo[1] = 1 fibo(n-1) print(" ".join(str(x) for x in memo))
values = [int(x) for x in raw_input().split(" ")] min = float('inf') for item in values: if item < min: min = item print(min)
def myStrcat(s1, s2): s3 = '' for s in s1: s3 += s for s in s2: s3 += s return s3 s1, s2 = [x for x in raw_input().split()] print(myStrcat(s1, s2))
import sys input = sys.stdin.readline().rstrip() if input.isalpha(): print("Alphabet") else: print("No")
n, m = [int(x) for x in raw_input().split(" ")] print("even" if (n & 1 == 0 and m & 1 == 0) or (n & 1 != 0 and m & 1 != 0) else "odd")
def isNumber(str): if str[0] != '-' and not str[0].isdigit(): return False if str[0] == '-' and len(str) == 1: return False for i in range(1, len(str)): if not str[i].isdigit(): return False return True input = raw_input() if (isNumber(input)): print("Yes") else: print("No")
n = int(raw_input()) digits = [] while n > 0: r = n % 10 if r & 1 != 0: digits.append(str(r)) n = n / 10 digits = reversed(digits) print(" ".join(digits))
str1=input("Input string: ") count=0 for i in range(len(str1)): if str1[i]!=" ": count+=1 print("Số ký tự có trong string:",count)
for j in range(2,11): print('') for i in range(2,11): print(f'{j}*{i}={j*i}')
import pandas as pd import matplotlib.pyplot as plt df = pd.read_json (r'./rain.json') print(df) print("df statistics: " ,df.describe()) df.plot(x='Month', y ='Temperature') df.plot(x='Month', y = 'Rainfall') plt.show()
sentence = input("Please enter a sentence: ") sentence.split() n = len(sentence.split()) result_line = "" for i in range(n): if i % 2 == 0: result_line += (sentence.split()[i]) + " " print(result_line)
time = int(input()) for i in range(time) : num, s = input().split() for i in s : print(i * int(num), end = '') print()
def fibo (i) : if i == 0 : return 0 if i == 1 : return 1 return fibo(i - 1) + fibo(i - 2) x = int(input()) print(fibo(x))
import math r = float(input()) print('%0.6f' % float(r*r*math.pi)) print('%0.6f' % float(r*r*2))
import math import os import random import re import sys def check(a, b): if len(b) > len(a): return False elif len(b) == len(a): if len(b) == 0 or b == a.upper(): return True else: return False else: if len(b) == 0: if a.lower() == a:...
import os import sys def findParent(node, parent): while not node == parent[node]: node = parent[node] return parent[node] def updateParent(node, parent, p): while parent[node] != p: tmp = parent[node] parent[node] = p node = tmp def roadsInHackerland(n, roads): roads.so...
import threading x=0 y=0 def func1(): global x for i in range(100000000): x=x+1 def func2(): global y for i in range(100000000): y=y+1 Th1 = threading.Thread(target=func1) Th2 = threading.Thread(target=func2) Th1.start() Th2.start() Th1.join() Th2.join() print(x,y)
x=int(input("Enter any number")) fac=1 for i in range(1,x+1): fac=fac*i print(fac)
def main(): user_number = int(input("Give a number: ")) print(" ") if user_number < 0: print("Your number is less than 0.") elif user_number == 0: print("Your number is 0") elif user_number > 0: print("Your number is bigger than 0") else: pr...
from myutils import * persons=[ { "name":"yerassyl1", "year":1998 }, { "name":"yerassyl2", "year":1997 }, { "name":"yerassyl3", "year":1999 }, ] ages = list(map(getAge,persons)) print(ages)
arr=[] print(arr,len(arr)) arr.append(10) print(arr,len(arr)) arr.append(20) print(arr,len(arr)) arr.append(30) print(arr,len(arr)) arr.append(40) print(arr,len(arr)) sumi = arr[0]+arr[1]+arr[2]+arr[3] print(sumi)
arr=[120,232,445,678] n = len(arr) for i in range(n): print(i,arr[i])
product={} product['name']="sdsdd" product['price']=1000 product['price']=12300 print(product)
num = int(input()) if num==5 or num==10: print("OK") else: print("Error")
s = "Hello world" n = len(s) s = s+"Yerassyl" print(s)
summa = int(input()) percent=0.0 if summa>=0 and summa<50000: percent = 1.3 elif summa>=50000 and summa<100000: percent = 1.6 elif summa>=100000 and summa<150000: percent = 1.9 else: print("Error") total_sum = summa+summa*percent/100 print(total_sum)
import os from myRedirect import redirect from shell import executeCommands import pipe '''This is the pipes method that take output of one method as input of another for example: output | input''' def pipeInput(args): left = args[0:args.index("|")] right = args[len(left)+1:] pRead, pWrite = os.pipe() ...
def analyze(data): """ Let's take a deeper look into the data """ persons = data.keys() POIs = filter(lambda person: data[person]['poi'], data) print('List of All People in the Data: ') print(', '.join(persons)) print('') print('Total Number of People:', len(persons)) print('') ...
def distinct(x): if x % 2 == 0: return "even" else: return "odd" print(distinct(3)) print(distinct(4))
import copy import numbers import math def map_dict(d, func): """ applies func to all the numbers in dict """ for (name,value) in d.items(): if isinstance(value, numbers.Number): d[name] = func(value) elif isinstance(value, list): for i in len(value): value[i]...
name = [] print ("enter 5 lowercase sentences and i will convert them to uppercase") for x in range (1,6): a = str(input()) name.append(a) for x in name: upper = (x.upper()) print(upper)
def Factorial(n): if n == 0 | n == 1: return 1 return Factorial(n-1)*n def Fibonaqi(n): if n == 1: return 0 if n == 2: return 1 return Fibonaqi(n-1)+Fibonaqi(n-2) print(Fibonaqi(30))
from math import sqrt class Triangle(object): def __init__(self, a, b, c): self._a = a self._b = b self._c = c @staticmethod def is_valid_static(a, b, c): return a + b > c and b + c > a and a + c > b @classmethod def is_valid_class(cls, a, b, c): return a + b > c and b + c > a and a + c > b de...
class FenwickTree: def __init__(self, exp): '''Creates a FenwickTree with range 0..(2^exp)-1''' self.exp = exp self.t = [0] * 2 ** (exp+1) def query_range(self, x, y): '''Gets the sum of the values in the range [x, y)''' return self.query(y) - self.query(x) de...
def bubble_sort(numbers): for i in range (len(numbers) - 1, 0, -1): for j in range (i): if numbers[j] > numbers[j+1]: temp = numbers[j] numbers[j] = numbers[j+1] numbers[j+1] = temp print(numbers) numbers = [5, 3, 8, 6, 7, 2] bubble_s...
def adjust(arr, parent, n): """ 调整二叉树 :param arr: 列表 :param parent: 父节点下标 :param n: 列表长度 """ temp = arr[parent] child = 2 * parent + 1 while child < n: if child + 1 < n and arr[child] < arr[child + 1]: child += 1 if temp > arr[child]: b...
import sys design=sys.argv[1] design_checked=sys.argv[2] def csv_parser(csv, csv_out): ERROR_STR = 'ERROR: Please check design file\n' def check_line_format(lspl): numCols = len(lspl) if numCols not in [4]: print (f"{ERROR_STR}Invalid num...
def get_student_top_notes(lst): ans=[] for i in lst: if len(i['notes'])>0: ans.append(max(i['notes'])) elif len(i['notes'])==0: ans.append(0) return ans print(get_student_top_notes([{"id": 1,"name": "Jacek", "notes": [5, 3, 4, 2, 5, 5]},{ "id": 2, ...
def count_words(txt): t = txt.split() return len(t) print(count_words("Just an example here move along")) print(count_words("This is a test")) print(count_words("What an easy task, right"))
def check(d1, d2, k): d1= { "sky": "temple", "horde": "orcs", "people": 12, "story": "fine", "sun": "bright" } d2 = { "people": 12, "sun": "star", "book": "bad" } if k in d1.keys() and k in d2.keys(): if d1[k]==d2[k]: return True elif d1[k]!=d2[k]: return 'Not the sa...
def empty_values(lst): l=[] for i in lst: if type(i)==int: l.append(0) elif type(i)==float: l.append(0.0) elif type(i)==str: l.append('') elif type(i)==bool: l.append(False) elif type(i)==list: l....
def is_powerful(num): i=1 l=[] while i<=num: if num%i==0: l.append(i) i=i+1 return l print(is_powerful(36)) print(is_powerful(27)) print(is_powerful(674))
def wumbo(words): return words.replace('M','W')
def percent_filled(lst): count=0 t=0 for i in lst: if ' ' in i: count=count+i.count(' ') t=t+i.count('o') if count==0: return '100%' return str(round(100*t/(count+t)))+'%' print(percent_filled(["###","#o#","###"])) print(percent_filled([ "####", "# #",...
def letter_counter(lst,letter): count=0 for i in lst: count=count+i.count(letter) return count print(letter_counter([ ["D", "E", "Y", "H", "A", "D"], ["C", "B", "Z", "Y", "J", "K"], ["D", "B", "C", "A", "M", "N"], ["F", "G", "G", "R", "S", "R"], ["V", "X", "H", "A", "S", "S"]], "D")) ...
def is_symmetrical(num): t=str(num) return t==t[::-1] print(is_symmetrical(7227) ) print(is_symmetrical(12567) ) print(is_symmetrical(44444444)) print(is_symmetrical(9939) ) print(is_symmetrical(1112111) )
class Country: def __init__(self, name, population, area): self.name = name self.population = population self.area = area self.is_big = self.population > 250000000 or self.area > 3000000 def compare_pd(self, other): this_density = self.popu...
def loves_me(num): l=['Loves me','Loves me not'] final_l=[] add=l[0] for i in range(0,num): final_l.append(add) if final_l[-1]==l[0]: add=l[1] else: add=l[0] final_l[-1]=final_l[-1].upper() return ', '.join(final_l) print(loves_me(3)) print(l...
def remove_vowels(st): l=['a','e','i','o','u'] ls=[] for i in st: if i not in l: ls.append(i) return ''.join(ls) def remove_vowels(string): vowels = "aeiou" for vowel in vowels: string=string.replace(vowel, "", ) return string print(remove_vowels("ben") ) pri...
def sum_even_nums_in_range(start, stop): count=0 for i in range(start,stop+1): if i%2==0: count=count+i return count print(sum_even_nums_in_range(10, 20) ) print(sum_even_nums_in_range(51, 150) ) print(sum_even_nums_in_range(63, 97) )
def consecutive_combo(lst1, lst2): t=lst1+lst2 sort=sorted(t) s='' for each in sort: s=s+str(each) maximum=max(t) minimum=min(t) for i in range(minimum,maximum+1): if str(i) not in s: return False return True print(consecutive_combo([7, 4, 5, 1], [2, 3,...
def sum_recursively(lst): if len(lst)==0: return 0 return lst[0]+sum_recursively(lst[1:]) print(sum_recursively([1, 2, 3, 4])) print(sum_recursively([1, 2]) ) print(sum_recursively([1]) ) print(sum_recursively([]) )
def letters_only(string): l=[] for i in string: if i.isupper() or i.islower(): l.append(i) return ''.join(l) print(letters_only("R!=:~0o0./c&}9k`60=y") ) print(letters_only("^,]%4B|@56a![0{2m>b1&4i4")) print(letters_only("^U)6$22>8p).") )
def fibonacci(num): a=0 b=1 for i in range(1,num+1): c=a+b a=b b=c return c print(fibonacci(3) ) print(fibonacci(7)) print(fibonacci(12))
def mini_peaks(lst): l=[] for i in range(1,len(lst)-1): if lst[i-1]<lst[i] and lst[i+1]<lst[i]: l.append(lst[i]) return l print(mini_peaks([4, 5, 2, 1, 4, 9, 7, 2])) print(mini_peaks([1, 2, 1, 1, 3, 2, 5, 4, 4])) print(mini_peaks([1, 2, 3, 4, 5, 6]))
def prime_numbers(num): count=0 i=1 while num: i=i+1 for j in range(2,i+1): if j>num: return count elif i%j==0 and i!=j: break elif i==j: count=count+1 break print(prime_numbers(10)) pr...
def how_many_times(msg): if len(msg)==0: return 0 current=msg[0] rest_of_string = msg[1:] char_int=ord(current)-96 return char_int+how_many_times(rest_of_string) print(how_many_times("abde")) print(how_many_times("azy")) print(how_many_times("qudusayo"))
import math def i_sqrt(n): if n < 0: return 'invalid' count = 0 while n >= 2: n **= 0.5 count += 1 return count print(i_sqrt(1)) print(i_sqrt(2)) print(i_sqrt(7)) print(i_sqrt(27)) print(i_sqrt(256)) print(i_sqrt(-1) )
def is_identical(s): return len(set(s))==1 print(is_identical("aaaaaa")) print(is_identical("aabaaa") ) print(is_identical("ccccca")) print(is_identical("kk"))
def next_in_line(lst, num): if len(lst)>0: t=lst.pop(0) r=lst.append(num) return lst else: return 'No list has been selected' print(next_in_line([5, 6, 7, 8, 9], 1)) print(next_in_line([7, 6, 3, 23, 17], 10)) print(next_in_line([1, 10, 20, 42 ], 6)) print(next_in_line([], 6)...
a = "John" b = "Joe" template = "My best friend is ." template.format(1).format(a, b) "{} these, not these {{}}".format("Substitute")
def emphasise(string): r='' for i in string.split(): t=(i[0].upper())+(i[1:].lower())+' ' r=r+t return r.rstrip() print(emphasise("hello world")) print(emphasise("GOOD MORNING") ) print(emphasise("99 red balloons!"))
def oldest(dict): a=max(dict[i] for i in dict) for k,v in dict.items(): if a==v: return k print(oldest({ "Emma": 71, "Jack": 45, "Amy": 15, "Ben": 29 }) ) print(oldest({ "Max": 9, "Josh": 13, "Sam": 48, "Anne": 33 }))
def is_in_order(txt): t=''.join(sorted(txt)) return t==txt print(is_in_order("abc")) print(is_in_order("edabit")) print(is_in_order("123")) print(is_in_order("xyzz"))
def alph_num(txt): l='' for i in txt: t=ord(i)-65 l=l+' '+str(t) return l.strip() print(alph_num("XYZ") ) print(alph_num("ABCDEF") ) print(alph_num("JAVASCRIPT"))
import math def vol_pizza(radius, height): t=(radius ** 2) * height *math.pi y=round(t,1) return round(y) print(vol_pizza(1, 1)) print(vol_pizza(7, 2)) print(vol_pizza(10, 2.5)) print(vol_pizza(15, 1.3))
def is_triangle(a, b, c): return a+b>c and a+c>b and b+c>a print(is_triangle(2, 3, 4)) print(is_triangle(3, 4, 5)) print(is_triangle(4, 3, 8)) print(is_triangle(2, 9, 5))