text
stringlengths
37
1.41M
# Assumptions: # 1. cypher text is hex string as ascii bytes (2 cypher text characters == 1 hex cypher text nibble) # 2. key length is between 2 and 30 # 3. plain text is ascii characters between 32 and 127 in decimal from collections import defaultdict import random chunk = 2 def get_pseudo_random_hex_key(key_len: i...
string_array = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] def int_to_str(number): str_number = "" if number == 0: return "0" while number > 0: digit = number % 10 number = int(number / 10) str_number = string_array[digit] + str_number return str_n...
from Queue import Queue from unittest import TestCase class QueueTest(TestCase): def setUp(self): self.queue = Queue() def test_enqueue(self): self.assertEqual(0, self.queue.size()) # size(queue) = 0 self.queue.enqueue(1) # queue -> 1 self.assertEqual(1, self.queue.size()) # si...
class PowerSet: def __init__(self): self.slots = list() def size(self): return len(self.slots) def put(self, value): if not value in self.slots: self.slots.append(value) def get(self, value): if value in self.slots: return True return F...
# https://skillsmart.ru/algo/py-kf32y/ce2fd8a857.html class _Node: def __init__(self, val): self.value = val self.next = None self.prev = None class _DummyNode(_Node): def __init__(self): super().__init__(None) class Queue: def __init__(self): self.head = _DummyNod...
# https://skillsmart.ru/algo/py-kf32y/a92175914c12.html class Node: def __init__(self, v): self.value = v self.prev = None self.next = None class OrderedList: def __init__(self, asc): self.head = None self.tail = None self.__ascending = asc self.length =...
c, d = 0, 1 for i in range(int(input())): a, b = int(input()), int(input()) c = c * b + a * d d = b * d x, y = c, d while y > 0: x, y = y, x % y print(c // x, '/', d // x, sep='')
from Stack import * def InfixToPostfix(expression): '''infix to postfix conversion''' # Precedence prec = {} prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 # Create an empty stack called data_stack for keeping operators. Create an empty list...
x = input("input a letter : ") if x == "a" or x == "i" or x == "u" or x == "e" or x == "o": print("This is a vowel!") elif x == "y": print("Sometimes y is a vowel and sometimes y is a consonant") else: print("This is a consonant!")
x = int(input("Input a number of sides (> 3):")) if x == 3: print("It's Triangle!") elif x == 4: print("It's Rectangle!") elif x == 5: print("It's Pentagon!") elif x == 6: print("It's Hexagon!") elif x == 7: print("It's Heptagon!") elif x == 8: print("It's Octagon!") elif x == 9: print("It'...
import tkinter as tk from tkinter import * from tkinter import font from tkinter import messagebox class SignupPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller # Labels label_type = tk.Label(self, text="® CopyRi...
def somaH(n): h = 0 # Elemento neutro da soma for i in range(1, n + 1): h += 1/i return h N = int(input("Digite N: ")) print("H = %.4f" % somaH(N))
import matplotlib.pyplot as plt import numpy as np x1 = np.linspace(-2, 2, 50)#起始值为-2,终值为2,生成50个等差数列 print(x1) y1 = 2*x1 + 1 plt.plot(x1, y1) #绘制曲线 ax = plt.gca()#获取当前影像 #plt.show() x=np.arange(0,2*np.pi,0.01)#半径范围 y=np.sin(x) ax.spines['bottom'].set_position(('data',0)) ax.spines['left'].set_position(('data',0))#...
#delete your tweets! import tweepy import ast print "Welcome to Serviette!" print "please register an app at twitter. This will be streamlined in the future" print "please set the app permission to 'read and modify tweets'" consumer_key = input("please paste your consumer key here ") consumer_secret = input("please pa...
def gcd(m, n): while m % n != 0: oldm = m oldn = n m = oldn n = oldm % oldn return n class Fraction: def __init__(self, num, denum): self.numerator = num self.denumerator = denum def __str__(self): return str(self.numerator) + '/' + str(self.de...
##################################################################### # Example : save an image from file (and invert it) # Author : Toby Breckon, toby.breckon@durham.ac.uk # Copyright (c) 2015 School of Engineering & Computing Science, # Durham University, UK # License : LGPL - http://www.gnu.org...
#COVID CSV CHECKER v0.11 #By Emilio Ramos from tkinter import filedialog import tkinter root = tkinter.Tk() root.filename = filedialog.askopenfilename(initialdir = "/", title = "Select file", filetypes = (("csv files","*.csv"),("all files","*.*"))) print (root.filename) #POINT TO JHU .CSV WITH...
# using this for logic flow on how to create more advanced game #simpel rock paper scissors import random def play(): user = input('r, s, p') computer = random.choice(['r', 's', 'p']) if user == computer: return 'Tie Game!' if win_lose(user, computer): return 'user won!' return '...
import os, sys print("HelloWorld") for i in range(32, 126): print( i, chr(i) ) words = ['apple', 'banana', 'peach', '42'] if 'apple' in words: print('found apple') if 'a' in words: print('found a') else: print('NOT found a') if 42 in words: print('found 42') else: print('NOT found 42')
""" You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps. You can either start from the step with index 0, or the step with index 1. Return the minimum cost to reach the top of the floor. - - - - - - - - Example 1: Input: ...
# 1 def buildPalindrome(string): if string == string[::-1]: # henc skzbic stugum enq polindrom e te che return string i = 0 while string[i:] != string[i:][::-1]: # stugum enq te vortexic minchev verj e gtnvum stringi substring polindrom@ i += 1 return string + string[i - 1::-1] # entarku...
import numpy import math class Vec3(numpy.ndarray): """ The Vec3 class implements the following: Public methods: v = Vec3() # several constructors are implemented v.normalize() v.translate() v.scale() v.rotateFromQuat() v.rotateFromEuler() v.rotateFromAxisAngle() v.getNorm() ...
# helper functions for treating float lists as quaternions # author: maxime.tournier@inria.fr import sys import math from numpy import * import numpy.linalg def id(): """identity""" return array([0, 0, 0, 1]) def conj(q): """conjugate""" return array([-q[0], -q[1], -q[2], q[3]]) def inv(q): """...
class Tile: # Class: Tile # Purpose: To act as the tiles that fill up the board, each tile can be used as a ship, or water def __init__(self): ''' Parameters: n/a Return: n/a Preconditions: Must create a Tile object. Postconditions: Sets the grid tile to "...
#Program - Remove Punctuations punct = '''@#$%^&!<>;"':''' mystr = "Myname!is@#Prash>:Nayakzzz;'" newstr = "" for ch in mystr: if ch not in punct: newstr = newstr + ch print(newstr)
#MAtrix Addition #Transpose Matrix - Ith row, jth col = jth row , ith col mat1 = [[1,5,3],[1,3,3]] mat2 = [[2,1,3],[2,1,3]] Sum = [[0,0,0],[0,0,0]] Transpose = [[0,0],[0,0],[0,0]] #------------------------------------------------------ for m1 in range(len(mat1)): print("Mat1:",m1) for m2 in range(len...
#Print Series of Fibanacci numbers using Recursion def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n-1) + fibonacci(n-2) for n in range(0,100): print(n , "Fibonacci:", fibonacci(n))
a = 500 b = -100 c = -522 if a >= b and a >= c: maxi = a elif b >= a and b >= c: maxi = b else: maxi = c print("Max NUmber is ", maxi)
#Program to shuffle Deck cards #Program to display month and year import itertools,random import calendar yy= 2019 mm = 6 print(calendar.month(yy,mm)) deck = list(itertools.product(range(1,14),["Shade","Dimond","Squre","Love","abx"])) random.shuffle(deck) for i in range(5): print(deck[i][0],"of",d...
even = [2, 4, 5, 6, 7, 9] another_even = list(even) #użycie '==' nie działa another_even.sort(reverse=True) print("Even jest rowne", even) print("another_even jest rowne", another_even)
import re def makeslug(st): """This will read a string as input and spaces and special charectors are replaced by a hyphen. More than one hyphwns and hyphen at the beginning are not allowed. """ out1 = re.sub(r'\W', '-',st) out2 = re.sub(r'-(-+)', '-', out1) if out2[0] == "-": ...
def anagrams(l): """Input a list of strings. Output a list of Anagrams. Two words are called anagrams if one word can be formed by rearranging letters of another. """ lnew = [] for i in l: for j in l: if len(i) == len(j) and equal(i,j): lnew.append((i,j)) p...
def cumulative_prod(l): """Prints the cumulative sum of a list of numbers: eg: input [a, b, c] output will be [a, a*b, a*b*c]. """ l_new = [] for i in l: if isinstance(i, int) or isinstance(i, float): l_new.append(i * prod(l[0 : l.index(i)])) return l_new def prod(l): """...
import sys def head(): """Prints head (first 10 lines) of the file. Input file name as command line argument """ fname = sys.argv[1] f = open(fname, 'r') for i in range(10): print f.next() f.close() head()
import string def mutate(word): """Input a word. Output all words generated by a single mutation on a given word. A mutation is defined as inserting a character, deleting a character, replacing a character, or swapping 2 consecutive characters in a string.Word should contain only small letters....
import time def profile(fn): """It takes a function as argument and returns a new function, which behaves exactly similar to the given function, except that it prints the time consumed in executing it. """ def g(arg): start = time.time() ans = fn(arg) end = time.time() ...
import urllib import re import sys def links(): """It takes a url as command line argument and print all urls linked from that page.""" url = sys.argv[1] web = urllib.urlopen(url) for i in web: out = re.findall(r'"http\S*"', i) for j in out: print j links()
import sys def parse_csv(): """Input: a C.S.V.(comma separated values) filename as command line argument. Output: Parsing line by line and printed. """ fname = sys.argv[1] f = open(fname, 'r') s = f.read() r = s.split() x = [] for l in r: a = l.split(',') x.append(a) ...
def json_encode(data): """This function encodes a python module into a JSON encoded type module """ if isinstance(data, bool): if data: return "true" else: return "false" elif isinstance(data, (int, float)): return str(data) elif isinstance(data, ...
# exercise A # 1. Create a variable name first with value 7. first = 7 # 2. Create a variable name second with value 44.3. second = 44.3 # 3. Print result of adding first to second. print(first + second) # 51.3 # 4. Print result of multiplying first by second print(first * second) # 310.0999 # 5. Print result of dividi...
#------------------------------------------------------------------------------ # Name: search_directory.py # Author: Kevin Harris # Last Modified: 02/13/04 # Description: This Python script demonstrates how to use os.path.walk() # and a call-back function to recursively walk ...
#------------------------------------------------------------------------------ # Name: hello_world.py # Author: Kevin Harris # Last Modified: 02/13/04 # Description: A very simple Python script for beginners. #------------------------------------------------------------------------------ ...
#------------------------------------------------------------------------------ # Name: create_radio_buttons.pyw # Author: Kevin Harris # Last Modified: 10/15/04 # Description: This Python script demonstrates how to create radio buttons. # # NOTE: To prevent a console from popping up when a ...
# # Поработайте с переменными, создайте несколько, выведите на экран, print('///////////////#1/////////////////////////////////////////////////////////') a = 12 b = 'строка' q, w, e, r, t, y = 1, 'qwe', 1.2, [1, 'sss', 3], (3, 4, 5), {2, 3, 4} print(f'---->---{q}-{w}-{e}--{r}----{t}----{y}---{a}--{b}->') print('///////...
# 2.Создать текстовый файл (не программно), # сохранить в нем несколько строк, # выполнить # подсчет количества строк, количества слов в каждой строке. with open('t2.txt', 'r', encoding='utf-8') as ff: res_lst = ff.readlines() print(res_lst) num_strings = len(res_lst) print(f'количество строк текста == ...
## 2.Реализовать класс Road (дорога), в котором определить атрибуты: ## length (длина), width (ширина). Значения данных атрибутов должны передаваться ## при создании экземпляра класса. Атрибуты сделать защищенными. # Определить метод расчета массы асфальта, необходимого для покрытия всего дорожного полотна. # Использов...
# 2. Представлен список чисел. Необходимо вывести элементы исходного списка, # значения которых больше предыдущего элемента. # Подсказка: элементы, удовлетворяющие условию, оформить в виде списка. # Для формирования списка использовать генератор. # Пример исходного списка: [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 5...
import numpy as np import pandas as pd import matplotlib.pyplot as plt m = 1000 x = 6* np.random.rand(m, 1) -3 y = 0.5 * x **2 + x + 2 + np.random.randn (m, 1) from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression poly_features = PolynomialFeatures(degree=2, include...
# Given two strings, return the minimum number of edits to turn str1 into str2 def minimum_edit_distance(str1, str2): memo = [[]] for str1_idx in range(len(str1)): for str2_idx in range(len(str2)): if str1_idx == 0: memo[str1_idx].append(0 if str1[str1_idx] == str2[str2_idx]...
class TrieNode: def __init__(self): self.children = dict() self.value = False class Trie: def __init__(self): self.root = TrieNode() def insert(self, word): node = self.root for char in word: if char not in node.chil...
class Solution: def letterCasePermutation(self, S: str) -> List[str]: result = [S] for i, c in enumerate(S): if c.isalpha(): result.extend([s[:i] + c.swapcase() + s[i+1:] for s in result]) return result class Solution: def let...
class Solution: def longestPalindrome(self, s: str) -> str: longest_string = '' if not s: return longest_string dp = [[False] * len(s) for _ in range(len(s))] for i in range(len(s)-1, -1, -1): for j in range(i, len(s)): dp[i][j] = (s[...
# For a positive n, fun2(n) prints the values of # n, 2n, 4n, 8n … while the value is smaller than LIMIT. # After printing values in increasing order, it prints # same numbers again in reverse order. def fun2(n): Limit=1000 if n<=0: return(print("Not entred correct value!")) if n>Limit: ...
# This program is calculating the # whole sum of any no with some addition # for e.g -> X=5 Y=2 then, # (x+y)+((x-1)+y)+....... def fun(X,Y): if X==0: return Y else: return(fun(X-1 ,X+Y)) inp1,inp2=int(input()),int(input()) print(fun(inp1,inp2)) # for better understanding visit to geeks for ...
def chooseCity(n, cities): answer = 0 min_distance = 0 for i in range(n): city_number = cities[i][0] distance = sum([abs(city[0] - city_number) * city[1] for city in cities if city[0] != city_number]) if min_distance == 0 or distance < min_distance: answer = city_number...
def getDayName(a, b): return ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'][(daysOfPreviousMonths(a) + b + 4) % 7] def daysOfPreviousMonths(month): return sum([daysOfMonth(m) for m in range(1, month)]) def daysOfMonth(month): return 31 if month in [1, 3, 5, 7, 8, 10, 12] else 30 if month in [4, 6, 9,...
#python3 def calc_fib(n): if (n <= 1): return n first = 0 second = 1 for _ in range (n-1): first, second = second, first + second return second n = int(input()) print(calc_fib(n))
# Formula for calculating the area of a square a,b,c,d,= 4,4,4,4 square_area = (int(a * b)) print(square_area) # Formula for calculating the area of rectangle a = 5 b = 10 rectangle_area = (int(a+b)) * 2 print(rectangle_area) # Formula for calculating the area of a trapezoid a = 5 b = 7 c = 7 d = 10 trapezoid_area ...
#day17 #Python Tuples 2 #Check if Item Exists thistuple = ("apple","cherry","banana") if "apple" in thistuple: print("yes,'apple' is in the fruits tuple") #Repeat Item thistuple = ("python",)*3 print(thistuple) #+ Operator in Tuple x = (3,4,5,6) x = x +(1,2,3) print(x) thistuple = ("apple","o...
#day 11 #Logical Operators x=5 print(x>3 or x<4) # returns true because on of the condation are true #Python Identity Operator x={"apple" , "banana"} y={"apple" , "banana"} z=x print(x is not z) # returns false because z is the same object as x print(x is not y) # returns true because x is not the sam...
#Python Dictionaries numbers = {n:('even' if n%2==0 else 'odd') for n in range(1,20)} print(numbers) ########## print('------------') ########## donations = dict(sam=25.0, lena=88.99, chuck=13.0, linuse=99.5, stan=150.0, lisa=50.25, harrison=10.0) total_donations = sum(donations.values()) print(tot...
#week 10 #Python Try-Except try: print(x) except: print('Error') #Finally try: print(x) except: print("somthing went worng") finally: print("the 'ty except' is finished")
#Python Dictionaries 3 #Copy a Dictionary thisdict = { "huda": "Almutairi", "city": "khobar", "year": 1997 } mydict = thisdict.copy() print(mydict) #Nested Dictionaries myFamily = { "sister1": { "name": "maali", "year": "1994", }, "sister2": { "name": "Afrah"...
### the purpose of this file is to simulate a dice rolling game import random from random import randint def diceRoll(): x = randint(1, 6) guess = int(input('Enter your guess: ')) print('You guessed', guess,'...', 'And the dice is...', x) if guess == x: print('Congrats! You win!') ...
#Topic ---- Association Rule Analysis !pip install mlxtend import numpy as np import pandas as pd import matplotlib.pyplot as plt from mlxtend.preprocessing import TransactionEncoder from mlxtend.frequent_patterns import apriori from mlxtend.frequent_patterns import association_rules import time import logging tr...
import string import re # load text filename = 'metamorphosis.txt' file = open(filename, 'rt') text = file.read() text file.close() text = text.replace('\n',' ') text # split into words by white space words = text.split() words # prepare regex for char filtering re_punc = re.compile('[%s]' % re.escape(string.pun...
import math import time def re_solution(n): n = int(n) if n == 1: return 0 if n%2 == 0: return 1 + re_solution(n/2) else: return 1 + min(re_solution(n+1), re_solution(n-1)) def solution(n): n = int(n) count = 0 while n != 1: if n...
import turtle import time import math turtle.shape('turtle') turtle.speed(3) def star(apex): count_apex=0 while count_apex<apex: turtle.forward(300) turtle.left(180-(360/(2*apex))) count_apex+=1 star(37) time.sleep(15)
def sum_dict(dict1): final_dict = sum(dict1.values()) return final_dict print(sum_dict({1:2,2:3,3:55,4:75,5:100})) #https://stackoverflow.com/questions/4880960/how-to-sum-all-the-values-in-a-dictionary
""" exercice v1 pour le jeu du pendu sur python """ #def lettre_dans_mot_a_deviner(lettre,mot_devin): #a in aba mot_devin = list(input('tape ton mot à deviner \n')) #le mot défini soluce = [w.replace(w,'-') for w in mot_devin] #le mot deviné cpteur_erreur = 0 lettre_deja_demande = [] while '-' in soluce: ...
def count_letter_dic(inp_str): stri = list(inp_str) out_dict = {} for item in stri: if item in out_dict.keys(): out_dict[item] += 1 else: out_dict[item] = 1 return out_dict print(count_letter_dic('aabcdeartmlqae'))
''' import collections d = collections.defaultdict(int) def day2_1(inputfile): with open(inputfile) as file: counter2 = 0 counter3 = 0 counter1 = 0 countfinal = 0 for line in file: frequencies = collections.Counter(line) countfinal +=1 #ok for key,value in frequencies.items(): #print(key,value...
# printing the number of digits present in a given number num_str = input("Enter a number: ") num = int(num_str) # print(type(num)) # print(len(num)) x = len(num_str) # initialize sum sum = 0 # find the sum of the cube of each digit temp = num while temp > 0: digit = temp % 10 sum += digit ** x temp //= ...
import math as m n = int(input("Enter the value: ")) x = m.sqrt(n) print("square root of", n, "is :", x)
import random EMPTY = "~" SHIP = "^" HIT = "X" MISS = "O" grid = [ [EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY], ] def add_random_ship(board): # Collect all positions that are empty - use the index of the row and column choices = [] for i, row in enumerate(board): ...
# 1. Write a function called add() which takes two positional parameters and # returns their values added together # 2. Write a function called average() which takes a single positional parameter # of a list, that calculates the average value of the list. The average is # calculated by adding all the values ...
import numpy as np import matplotlib.pyplot as plt #ROTATION MATRIX FOR X AXIS def rotateX(p, ang): m_rot = np.array([ [1,0,0], [0, np.cos(np.deg2rad(ang)), -np.sin(np.deg2rad(ang))], [0, np.sin(np.deg2rad(ang)), np.cos(np.deg2rad(ang))] ]) rot = m_rot @ p return rot #ROTATI...
from unittest import TestCase from monopoly import ImpulsivePlayer class PlayerTest(TestCase): def setUp(self) -> None: self.player = ImpulsivePlayer() self.player.balance = 10 def test_player_should_buy_if_balance_allow_it(self): self.assertTrue(self.player.should_buy(9)) sel...
from math import * # function f(x) def f(x): return log(x) # function derivative 2-th of f(x) def df2(x): return 0 - 1 / pow(x, 2) # function derivative 4-th of f(x) def df4(x): return 0 - 6 / pow(x, 4) # oscillating function def F(x, w): return f(x) * sin(w * x) # imaginary polynomial def iD(index...
class Parameter: def __init__(self, name, value, quantity_space): self.__name = name self.__value = value self.__quantity_space = quantity_space @property def name(self): return self.__name @property def value(self): return self.__value @property de...
# ##Start Excercise_________________________________________ # Exercise 1: Ran code in terminal # import random #  random.randint(5, 10) # 10 #  random.randint(5, 10) # 9 #  t =[21,22,32] #  random.choice(t) # 21 #  t=[1,3,6] #  random.choice(t) # 1 #  t=[32,20,33] #  random.choice(t) # 33 # ##Start Excercis...
format = 'Hello, %s. %s enough for ya?' values = ('world', 'Hot') print(format % values) from string import Template tmp1 = Template("$test") str1 = tmp1.substitute(test = 'yes') print(str1) tmpl = Template("Hello, $who! $what enough for ya?") str1 = tmpl.substitute(who="Mars", what="Dusty") print(str1) str1 = "I ...
""" Commonly used text preprocessings """ import string, sys import numpy as np def base_filter(): """ return all the punctuations strings we want to remove from the text """ f = string.punctuation f = f.replace("'",'') # we want ' in the text f += '\t\n' return f def text_to_word_sequen...
# ARTIFICIAL NEURAL NETWORK #------------------------------------------------------------------------------------# #---------------------------- PART I: DATA PREPROCESSING ----------------------------# #------------------------------------------------------------------------------------# # Importing the libraries impo...
import string def add_vectors(u, v): """ >>> add_vectors([1, 0, 2], [1, 1, 1]) [2, 1, 3] >>> add_vectors([1, 2], [1, 4]) [2, 6] >>> add_vectors([1, 2, 1], [1, 4, 3]) [2, 6, 4] >>> add_vectors([11, 0, -4, 5], [2, -4, 17, 0]) [13, -4, 13, 5] """ i = 0 w = [] while i <...
def cat_n_times(s, n): print s*n cat = [1, 2, 3] print "Cat is %r" %(cat) x = "There are %d types of people" %10 binary = "binary" donot = "don't" y = "Those who know %s and those who %s" %(binary, donot) print x print y print "I said: %r" %x print "I also said: '%s'" %y hil = False joke = "Isn't this joke f...
p=float(input("Enter the Principle Amount: ")) n=float(input("Enter the Duration(in years) : ")) r=float(input("Enter the Rate of Interest: ")) simple_interest=(p*n*r)/100 print("The simple interest is: ",simple_interest)
'''Longest Palindromic Substring''' #Solution I: Brute Force def solve(str): palin=[] for i in range(len(str)-1): for j in range(i+1,len(str)): if str[i:j]==str[i:j][::-1]: palin.append(str[i:j]) return max(palin,key=len), len(max(palin,key=len)) def solve1(str): l=...
#Recursive Solution def fact(n): return 1 if n==0 or n==1 else n*fact(n-1) #Iterative Solution #Driver Code if __name__ == "__main__": print(fact(9))
#Encryption import string def encrypt(plain_text, n): alphabets = list(string.ascii_lowercase) encrypted=[] for i in plain_text: if n>0: char_index=alphabets.index(i) char_index+=n charAt=alphabets[char_index] encrypted.append(charAt) elif n<0...
'''Python | Split string into list of characters''' def solve(str1): l=[] for i in range(len(str1)): if str1[i] != ' ': l.append(str1[i]) return l #List Comprehension def solve1(str1): return [i for i in str1] #Type Casting def solve2(word): return list(word) #Drive...
'''How do you find all the permutations of a string?''' #Recursive Solution def permutate(s, step=0): if step == len(s): print(''.join(s)) for i in range(step, len(s)): copy=[c for c in s] copy[step],copy[i]=copy[i],copy[step] permutate(copy,step+1) #Usin built-in API from ite...
class Node: def __init__(self, data=None,next=None): self.data=data self.next=next class LinkedList: def __init__(self): self.head=None def insert_start(self,data): node=Node(data,self.head) self.head=node def print(self): if self.head is None: ...
'''Python | Remove empty strings from list of strings''' def solve(s): return [i for i in s if i] def solve1(s): while('' in s) : s.remove('') def compress(chars): dict={};temp='';c=1 for i in range(len(chars)): if chars[i] not in dict: dict[chars[i]]...
# name = input() # # print('name') # print("Hello, " , name) # print("Hey Jude," "Do not make it bad") # a = 'ABC' # b = a # a = 'XYZ' # # print('a is', a,'b is', b) # print(first_name + " " + last_name) # # first_name = 'john' # last_name = 'lennon' # name = first_name + " " + last_name # print("hello, {}! You are {...
import math from Isotope import Isotope from Decay import Decay def main (): # Receive isotope data decayConstant = float (input ("Decay Constant: ")) arrayLength = int (input ("Array Length: ")) timeStep = float (input ("Time Step: ")) iterations = int (input("Iterations: ")) ...
# printng first code print('hello world') # variables # if you want to create variables with more than 1 word, use underscore age = 20 age = 30 first_name = 'sai' is_Online = False print(age) # exercise name = 'john smith' age = '20' is_new_patient = True # receiving input from user input('what is your name? ') #...
""" ####################################################### functions with inputs def my_function(param): # do something # do something else my_function(arg) ####################################################### """ import math import random # a simple function name = input('What is your name? ') def greet()...
''' ################################################################## TIP CALCULATOR PROJECT # If the bill was $150.00, split between 5 people, with 12% tip. # Each person should pay (150.00 / 5) * 1.12 = 33.6 # Format the result to 2 decimal places = 33.60 #######################################################...
#!/usr/bin/env python3 import itertools """ """ def welcome(): return "Welcome to the scheduler" def workday_map(sched): daymap = [] for ons, offs in sched: daymap.extend(itertools.repeat(True, ons)) daymap.extend(itertools.repeat(False, offs)) return daymap def is_workday(sched, days...