text
stringlengths
37
1.41M
# THIS IS CHALLENGE # define a function take any no of lists containing any number # [1,2,3] , [4,5,6], [7,8,9] # return average # (1+4+7)/3, (2+5+8)/3, (3+6+9)/3 # def average_finder(l1, l2, l3): # average = [] # for pair in zip(l1,l2, l3): # average.append(sum(pair)/len(pair)) # return average ...
# return vs print # return store the function value # print show the function value # def add_three(a,b,c): # return a+b+c # Store values in function # add_three(5,5,5) # print nothing # print(add_three(5,5,5)) # Now it prints 15 def add_three(a,b,c): print(a+b+c) # print values in fu...
# word counter def word_counter(s): dic = {} for i in s: dic[i] = s.count(i) return dic print(word_counter('vivek'))
# function returning function def outer_func(): def inner_func(): print("Inside inner function") return inner_func var = outer_func() var() def outer_func2(msg): def inner_func2(): print(f"Message is {msg}") return inner_func2 msg = outer_func2('Hello ther !') msg()
# create a laptop class with attributes like name, model, price # create two objects/instance of your laptop class class laptop: def __init__(self, brand, model, price): self.brand = brand self.model = model self.price = price self.name = brand + ' ' + model laptop1 = laptop('IBM',...
# lambdas expressions (anonymous function) def add(a,b): return a+b print(add(2,3)) add2 = lambda a,b : a+b print(add2(4,5)) multiply = lambda a,b : a*b print(multiply(3,4)) print(add) print(add2) print(multiply)
# Exception handling # try except else finally while True: try: age = int(input('Enter yur age: ')) # seven # 7 break except ValueError: print('maybe you entered string insteat of number, try again') except: print('unexpected error...') if age < 18: print('You can\'t pl...
for i in range(1, 3): name = input("Enter Name : ") age = input("Enter age : ") gender = input("Enter gender : ") marks = input("Enter marks : ") school = input("Enter school : ") data = {} data["name"] = name data["age"] = age data["gemder"] = gender data["marks"] = marks ...
#!/usr/bin/env python # encoding: utf-8 """ :Description:输出一个str的所有子序列 :Author: 佳境Shmily :Create Time: 2020/4/19 22:12 :File: 输出一个str的所有子序列 aaa的子序列 a(1),a(2),a(3),aa(12),aa(23),aa(13),aaa(123) :Site: shmily-qjj.top 以arr=[1,2,3]为例,用01二进制串决定子序列中的每个数字是否输出。0表示该位置上的数字不存在,1表示该位置上的数字存在 子序列如果是空集[],就用000表示,因为[1,2,3]中没有元素存在;子序列...
#!/usr/bin/env python # encoding: utf-8 """ :Description:Threading运行三个不同线程 :Author: 佳境Shmily :Create Time: 2022/1/10 14:31 :File: ThreadingTest :Site: shmily-qjj.top """ import threading import time s = set() # 全局变量 def a(): for i in range(1, 5): if i not in s: # 输出过的数字就不打印了 s.add(i) # 向集...
#!/usr/bin/env python # encoding: utf-8 """ :Description: 队列 queue :Author: 佳境Shmily :Create Time: 2020/3/17 15:27 :File: queue :Site: shmily-qjj.top 栈的特点是后进先出(LIFO),队列的特点是先进先出(FIFO) 队列的基本方法 count:获取Queue中包含的元素个数 clear():从Queue中移除所有的元素 contains(object obj):判断某个元素是否在Queue中 Dequeue():移除并返回在Queue的开头的对象 Enqueue(object obj...
#!/usr/bin/env python # encoding: utf-8 """ :Description:剑指Offer 17 :Author: 佳境Shmily :Create Time: 2020/4/28 11:59 :File: Solution17 :Site: shmily-qjj.top 输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构) """ # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.ri...
# -*- coding: UTF-8 -*- """ :Description: sched模块是 Python 内置的模块,它是一个调度(延时处理机制),每次想要定时执行某任务都必须写入一个调度。 :Owner: shmily :Create time: 2022/9/5 14:09 """ import sched import time from datetime import datetime # 初始化sched模块的 scheduler 类 # 第一个参数是一个可以返回时间戳的函数,第二个参数可以在定时未到达之前阻塞。 schedule = sched.scheduler(time.time, time.sleep...
#!/usr/bin/env python # encoding: utf-8 """ :Description: 其他公司 笔试编程题 及 实现 :Author: 佳境Shmily :Create Time: 2020/3/22 0:18 :File: Solutions :Site: shmily-qjj.top """ # def solution(): # """ # 有一张包含n行m列的方格纸,每个小方格都是一个基地(总共有n*m个基地) # 现在要放置补给品,如果补给品落在小方格内或边界上则该基地获得了补给品 # 如果补给点在交界处,则被视为已为交界的单元格都提供了补给品(如果在两个格子的...
#An if statement eveluates a statement and only executes if it is true #A variable to evaluate in the if statement b = True #When comparing variable like b to another value, you must use == and not =. == checks the variables value where as = assigns a new value to that variable #You must also indent all the code that...
__author__ = 'stefan' """=================================================================================================== When some people receive change after shopping, they put it into a container and let it add up over time. Once they fill up the container, they'll roll them up in coin wrappers which can then b...
""" Sudoku is a number-placement puzzle. The objective is to fill a 9 × 9 grid with numbers in such a way that each column, each row, and each of the nine 3 × 3 sub-grids that compose the grid all contain all of the numbers from 1 to 9 one time. Implement an algorithm that will check whether the given grid of numbers...
#howv to search in a list using function """ def search(list,n): #my search functio i = 0 while i <len(list): if list[i] ==n: return True; i +=1 return False; list = [5,3,6,7,3,4] n = 6 if search(list,n): print("found at",list.index(n)) else: print("not found")...
#!/usr/bin/env python # coding: utf-8 # In[3]: str = "I am very keen in building up my career in Data Science, but not sure from where to start. If I search the web it throws me thousands of articles, few are relevant others make me confused, again I come around to the same page. Supervised has provided me a good pl...
""" Evaluate the predictive fit of a slum map against the ground truth. -- Scripts evaluate(pred, truth, mask): script to convert pngs to masked arrays, compile metrics of fit and print a results table. Args -- pred: predicted slum map; truth: ground truth slum map Optional args -- mask: area-of-interest mask. Exa...
lst = [0, 1] def fibonacci (value = int(input("Enter number of numbers in sequence: "))): for i in range(value-2): lst.append( lst[len(lst)-1] + lst[len(lst)-2]) fibonacci() print(lst)
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def partition(self, head, x): """ :type head: ListNode :type x: int :rtype: ListNode """ if head is None: ...
class Solution(object): def count_append(self, maxWidth, nowLen, nowline): sp= (maxWidth - nowLen) wsp = [0] * len(nowline) flag = 0 for i in range(0, sp): wsp[flag] += 1 if len(nowline) - 1 > 0: flag = (flag + 1) % (len(nowline) - 1) ...
class Solution: def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: bool """ begin = 0 end = len(nums) - 1 while begin <= end: mid = (begin + end) // 2 if nums[mid] == target: retu...
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if len(strs) == 0: return "" ret = "" i = 0 while True: c = None for s in strs: if len(s) <= i: ...
import speech_recognition as sr from src.reader import Reader class AudioReader(Reader): """A class based on the speech recognition package for an audio file.""" RECORD = { "en-US": "Is Loading!", "fa-IR": "در حال بارگزاری!" } def __init__(self, audio_file, *args, **kwargs): ...
def permute(s, i, t): if i == t: print(s) else: for rec in range(i, t + 1): s[i], s[rec] = s[rec], s[i] permute(s, i + 1, t) s[rec], s[i] = s[i], s[rec] #backtrack s = list('ABC') i = 0 t = len(s) permute(s,i,t-1)
import matplotlib.pylab as plt # This function divides an array into chunks to be used in the graph # as alternating colours. This is achieved by having each colour have # its own set of data and graph all taken from the original graoh def Filter(array, nr_colours, choice): result = [] for i in range(le...
def check_parantheses(st): cnt_par = 0 cnt_bra = 0 cnt_cur = 0 # count parantheses () for el in st: if el == '(': cnt_par += 1 if el == ')': cnt_par -= 1 if cnt_par < 0: return False # count brackets [] for el in st: if el == '[': cnt_bra += 1 if el == ']': cnt_bra -= 1 if cnt_bra < 0:...
import time start = time.time() import math primes=[2,3] a=5 while a<1000000: b=math.sqrt(a) for x in primes: if a%x==0: break if x>b: primes.append(a) break else: primes.append(a) a=a+2 def pfact(n): p=[] a=0 while n>=primes[a]**2: if n%primes[a]==0: p.append(primes[a]) while n%primes[a...
from math import factorial as fact def run(): count = 0 for n in xrange(23, 101): r = 1 fn = fact(n) while fn / fact(r) / fact(n - r) < 10**6: r += 1 o = 2 * (int(n / 2) + 1 - r) - (1 if n % 2 == 0 else 0) count += o return count from runner import main ...
import numpy as np arrayPesos = [1.5, 0.5, 1.5, 0.5] salidaEsperada = [0, 0, 0, 1, 0, 1, 1, 1] alfa = 1 entradas1 = [1, 0, 0, 0] entradas2 = [1, 1, 0, 0] entradas3 = [1, 0, 1, 0] entradas4 = [1, 1, 1, 0] entradas5 = [1, 0, 0, 1] entradas6 = [1, 1, 0, 1] entradas7 = [1, 0, 1, 1] entradas8 = [1, 1, 1, 1] entradas = [ent...
'''a1_fn_sig_checker.py Function signature checker, for Assignment 1, in CSE 415, Winter 2020. ''' import a1 print("Checking is_multiple_of_3") for arg in [-6, -1, 0, 11, 18, 3.0]: answer = a1.is_multiple_of_3(arg) if not answer in [True, False]: print("Warning: your function is_multiple_of_3 returned a ...
#dont give the filename for this program as calendar #it will give the error " Module 'calendar' has no 'month' member " import calendar year=int(input("Enter the year: ")) month=int(input("Enter the month(1-12): ")) print (calendar.month(year,month))
""" CMPS 2200 Recitation 1 """ ### the only imports needed are here import tabulate import time ### def linear_search(mylist, key): """ done. """ for i,v in enumerate(mylist): if v == key: return i return -1 def test_linear_search(): """ done. """ assert linear_search([1,2,3,4,5], 5) == 4 assert linear_s...
# hello.py # -*- coding: utf-8 -*- from types import MethodType class student(object): #use __slots__ to lock attr __slots__ = ('name', 'score', 'show', 'height', '__name', '__score', '__height') #__str__ is for print this class def __str__(self): return 'student str is '+self.name __repr__ = __str__ def __ini...
import numpy as np def sigmoid(x): """ Calculate sigmoid """ return 1 / (1 + np.exp(-x)) x = np.array([0.5, 0.1, -0.2]) target = 0.6 learnrate = 0.5 weights_input_hidden = np.array([[0.5, -0.6], [0.1, -0.2], [0.1, 0.7]]) weights_hid...
''' The total number of months included in the dataset The net total amount of "Profit/Losses" over the entire period The average of the changes in "Profit/Losses" over the entire period The greatest increase in profits (date and amount) over the entire period The greatest decrease in losses (date and amount) over ...
import math def main(): values = [int(round(func(x / 256.0) * 255)) for x in range(256)] values_hex = [hex(x) for x in values] print ",\n ".join([", ".join(values_hex[i*16:(i + 1) * 16]) for i in range(16)]) def func(x): return (1 - math.cos(x * math.pi)) / 2 main()
import math import random import matplotlib.pyplot as plt import csv # Given Problem def fitness_eqn(x_dict): try: with open("equation.txt") as eqn_file: expression = eqn_file.readline() except: print("\n\tEquation file is not present.") exit(1) return eva...
# # Definition for binary tree: # class Tree(object): # def __init__(self, x): # self.value = x # self.left = None # self.right = None def isTreeSymmetric(t): tr=t # carry out a symmetric DFS return checkSym(t,tr) def checkSym(lb,rb): if lb and rb: if lb.value != rb.value: ...
def autocomplete(wordList,actions): #crete tree t=Trie(None,wordList) t.createTree() s='' ACL=[] for e in actions: if e == "PAUSE": ACL.append(list(t.findNode(s))) elif e == "BACKSPACE": s=s[:-1] else: s+=e return ACL c...
# Definition for singly-linked list: # class ListNode(object): # def __init__(self, x): # self.value = x # self.next = None # def reverseNodesInKGroups(l, k): rem=l pn=ListNode(-1) snode=pn while rem: pn.next,rem,pn=revListNode(rem,k) return snode.next def revListNode(cpoint,...
# Definition for singly-linked list: # class ListNode(object): # def __init__(self, x): # self.value = x # self.next = None # def removeKFromList(l, k): st=l while st and st.value==k: st=st.next l=st while l and l.next: if l.next.value==k: l.next=l.next.next ...
from __future__ import absolute_import, division, print_function, unicode_literals import pandas as pd from sklearn.preprocessing import MinMaxScaler from sklearn.cluster import KMeans # Create training and testing datasets train = pd.read_csv(r'C:\Users\Admin\Desktop\Programming Applications and Projects\Datasets\Co...
# -*- coding: utf-8 -*- """ Created on Thu Jul 9 14:34:41 2020 @author: stdon """ def gcd(m,n): while m%n != 0: oldm = m oldn = n m = oldn n = oldm%oldn return n class Fraction: def __init__(self,top,bottom): assert all (isinstance(i, int) for i in [top, bottom...
import Tkinter as tk class Scroll(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller # create a canvas object and a vertical scrollbar for scrolling it self.canvas = tk.Canvas(self, bd=0, highlightthickness=0)...
import numpy as np class Layer(object): """This class represents a layer of the Neural Network.""" def __init__(self, number_of_neurons,layer_type='hidden',layer_activation='relu' ,dropout=False,keep_prob=0.75): """Constructor of Layer class""" self.number_of_neurons = number_of_neurons self.layer_type = l...
#MODULE 7 - Pythin Turtle graphics #https://docs.python.org/3/library/turtle.html (Links to an external site.) #Before using turtle install turtle graphics. #sudp apt install python3-tk python-tk # #Try this code: import turtle import random import math w = turtle.Screen() w.bgcolor("#000000") t = turtle.Turtle() t....
f_n=input("Enter the name of the first person\n") f_n=f_n.replace(' ','') #Removing Space s_n=input("Enter the name of the second person\n") s_n=s_n.replace(' ','') #Removing Space #identify which name has more character if len(f_n)>=len(s_n): f_n_list=list(f_n) s_n_list=list(s_n) ...
from kNN import * import numpy as np def datingClassTest(): hoRatio = 0.10 datingDataMat, datingLabels = file2matrix('datingTestSet2.txt') normMat, ranges, minVals = autoNorm(datingDataMat) m = normMat.shape[0] numTestVecs = int(m * hoRatio) errorCount = 0.0 for i in range(numTestVecs): ...
#!/usr/bin/env python # Name: Jacob Vermeule # Student number: 11328622 """ This script scrapes IMDB and outputs a CSV file with highest rated movies. """ import csv from requests import get from requests.exceptions import RequestException from contextlib import closing from bs4 import BeautifulSoup soup = BeautifulSo...
fname = raw_input("Enter file name: ") try: fh = open(fname, 'r') except: print 'No such file. File cannot be opened:', fname exit() count = 0 for line in fh: line = line.rstrip() if not line.startswith('From '): continue words = line.split() count = count + 1 print words[1] print "There were", count, "line...
# Luis Fernando Koh Avila # Data 2 B # My example seeing the incomes from an enterprise during 2019, 2020, 2021 import matplotlib.pyplot as plt plt.style.use('seaborn-colorblind') # Taking a style for the plot months_x = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"] # X axis with the month...
import os import pandas as pd import numpy as np import requests import time import re import string def get_book(url): """ get_book that takes in the url of a 'Plain Text UTF-8' book and returns a string containing the contents of the book. The function should satisfy the following conditions: ...
try: revolutions = float(input("Введіть кількість обертів Марсу: ")) earthRevolutions = round(686 * revolutions / 365, 1) if revolutions <= 0: raise ValueError print(f'{revolutions} обертів Марсу = {earthRevolutions} обертів Землі') except ValueError: print('\nПомилка! Введіть додатнє число!...
''' Python script that reads in text that is to be given a keyword matching weight number The objective is to match keywords with text such as an article description, the article title, the content of the article, or any other text that is to be weighted against the inputed keywords. Returns an integer that represents...
''' Python script that is to familierize myself to the workings about how pyhon interacts with a Sqlite database, and then ultimatly use this to create a python script to find and save articles to the database for futher use. Author: Founding Fathers, Kristian Nilssen Date: 2/10/2017 Usage: python mysql_article_...
#!/usr/bin/env python3 """Parses the text of Unsong, and the list of chapter initials, and finds longest common subsequences. The idea here is that if the notarikon formed by the first letter of each chapter conceals a secret message, then perhaps parts of that message have already been revealed in the book... so if...
import re result = re.search(r"aza", "plaza") print(result) result = re.search(r"aza", "bazaar") print(result) result = re.search(r"aza", "maze") print(result) print("......................") #strict beginning print(re.search (r"^x", "xenon")) print(re.search (r"^xe", "xenon")) print("......................") # wildC...
import re # print(re.search(r"p.*ng", "Penguin", re.IGNORECASE)) # '\w*' : matches alphanumeric and __ - # charater classes are run inside square-brackets, # and let us list the char we want to match is of those bracket #print(re.search()) # print(re.search(r"[a-z]*way", "The end of the highway")) print('-------======...
import re rearrange = re.sub(r"^([\w .-]*), ([\w .-]*)$", r"\2 \1", "Saalu, Issaka") # print(rearrange) print("=========Print Function======") def rearrange_name(name): regex = re.sub(r"^([\w .-]*), ([\w .-]*)$", r"\2 \1", name) if name is None: return "Doesn't Match!" return regex print(rearran...
import re # Regex in action def test_func(testing): regex = re.search(r"[a-zA-Z]{5}", testing) regex = re.search(r"\w{5,10}", testing) regex = re.findall(r"\b[a-zA-Z]{5,10}\b", testing) return regex print(test_func('a scary ghost appeared')) print('-----seperator-----') print(test_func('I really ...
#!/usr/bin/env python3 # encoding: UTF-8 ########################################################################## # # CS 160 - Week 5 Exercise # Purpose: Unordered Linked List Implementation # # Author: Ahmad M. Osman # Date: March 4, 2017 # # Filename: ulinkedlist.py # ##############################################...
#!/usr/bin/python3 def read_a_number(): n = int(input("Enter a positive number> ")) if n > 0: return n else: raise Exception("This is not a positive number") if __name__ == "__main__": print("---IMPORTANT---") print("'finally' does not work properly in Trinket!") print("Copy...
#!/usr/bin/env python3 # encoding: UTF-8 ########################################################################## # # CS 160 - Week 6 Project # Purpose: Card Game Snap Simulation # # Author: Ahmad M. Osman # Date: March 16, 2017 # # Filename: CardGame.py # ############################################################...
#!/usr/bin/env python3 # encoding: UTF-8 ############################################################################ # # CS 160 - Week 8 Exercise # Purpose: Searching Algorithms & Hash Function(s) # # Author: Ahmad M. Osman # Date: April 1, 2017 # # Filename: Card.py # ################################################...
#!/usr/bin/env python3 # encoding: UTF-8 ########################################################################## # # CS 160 - Week 5 Exercise # Purpose: Palindrome Checker Extension To Ignore Spaces # # Author: Ahmad M. Osman # Date: March 4, 2017 # # Filename: palch.py # ###########################################...
#!/usr/bin/env python3 # encoding: UTF-8 ########################################################################## # # CS 160 - Week 5 Exercise # Purpose: Linked List Class Implementation # # Author: Ahmad M. Osman # Date: March 4, 2017 # # Filename: linkedlist.py # ###################################################...
##coding:cp949 #from abc import abcmeta, abstractmethod #class terran(metaclass=abcmeta): # def __init__(self , name): # self.name = name # @abstractmethod # def attack(self): # pass # #class tank(terran): # def __init__(self , name , damage): # super().__init__(self , name) # ...
import speech_recognition as sr import nltk nltk.download('punkt') nltk.download('averaged_perceptron_tagger') ''' print("Read your daily article and press the button when done") article = scrape_article() display_article(article) questions = generate_questions(article, 3) ''' ''' questions = { "Hello, how are y...
FILENAME = 'input.txt' def load_lines(filename): with open(filename) as file: return file.read().splitlines() def get_records(line_parts): records = [] for line_parts in line_parts_collection: length_parts = line_parts[0].split('-') length = int(length_parts[0]), int(length_parts[1...
from collections import defaultdict def calculate_distance(coord1, coord2): return abs(coord1[0] - coord2[0]) + abs(coord1[1] - coord2[1]) def get_coords(): f = open('6.txt') lines = f.read().splitlines() coords = [] for line in lines: coord = line.split(', ') coord = (int(coord[0]...
import random from random import randrange import matplotlib.pylab as plt from operator import itemgetter dress_code = input("Enter the Dress code you want: ") # dress code color = input("Enter the Color you want: ") # dark or bright user_money = float(input("Enter the budget you have (as float): ")) # budget genera...
# a=int(input('xxxx')) # b=int(input('xxxx')) # c=int(input('xxxx')) # if a+b>c and b+c>a and c+a>b: # print('xxxxx') # print('c=',(a+b)/c) # else: # print('xxxx') # list1=[] # for x in range(2,51): # n=x/2 # # print(n) # list1.append(n) # # print(list1) # # print(list1[0],list1[3]...
import random from math import floor from math import ceil from random import randrange import numpy as np class BetException(Exception): pass class InvalidBetException(BetException): #Raised when a bet does not have either a higher quantity or a higher value pass class Bet(object): def __init__(self, bet): ...
import numpy def edit_distance(correct_ans, student_ans): """ :param correct_ans: correct answer, can be multiple words :param student_ans: answer submitted by student, can be multiple words :return The Edit Distance between 2 strings """ len_correct_ans = len(correct_ans) len_student_ans...
# File Objects # using context manager. benefit of using with is it will open and close the file automatically # with open('test.txt', 'r') as f: # this is for reading the entire file #f_contents = f.read() # what if the file is too large? then just read the file using readlines as the lines of contents in file as ...
"""Module for working with a file""" import sys import re from config import * text = {} def get_text(filename): """ Getting a text from a file """ try: f = open(filename, "r") except FileNotFoundError: print("Not found file \"{0}\"".format(filename)) return "" text =...
dictionary = {} current_number = 0 def enumerate_words(list_): ''' Enumerates words and return a list of numbers ''' global dictionary, current_number result_list = [] for word in list_: try: value = dictionary[word] except KeyError: value = current_numbe...
# Cesar Cortez # PSID = 1836168 import datetime def date_parser(dates): current_date = datetime.datetime.now() current_date_string = str(current_date) current_year = int(current_date_string[0:4]) current_month = int(current_date_string[5:7]) current_day = int(current_date_string[8:10]) mont...
from random import randint #Global variable for answers or responses responses = ['It is certain','It is decidedly so','Without a doubt','Yes - definately','You may rely on it', 'As I see it, yes','Most likely','Outlook good','Yes','Signs point to yes','Reply hazy, try again', 'Ask again later...
from lib_class import * Customer_List=[] op11=1 while op11 !=4: print("\t order ") print("\t1.Entry") print("\t2.View") print("\t3.Product Count:") print("\t4.Exit") op11=int(input("Enter Your option :")) if op11==1: op1="yes" while op1=="yes": c1=Customer() ...
''' Inheritance : - is the proccess by which object of one class can access or get the properties of objects of another class. A a1 B b1 a1 --> b1 1) Single Inheritance : one object access or get the properties of only one object at a time. A | B 2)Multilevel Inheritance : continous cha...
from functools import reduce ''' 1) Implemente de maneira iterativa e recursiva a operação soma_elementos(). Esse método deve receber como parâmetro uma lista ou vetor contendo números e retornar a soma dos elementos dest...
#even fibonacci numbers sum ##first, second = 1,2 ##nxt = 0 ##n = 100 ##s = 0 ##while second<4000000: ## nxt = first +second ## if second%2==0: ## s += second ## first = second ## second = nxt ## ##print(s) #efficient #in fibo seq every third element is even #so only the third number is added #1 1...
# Given a string, return a new string made of n copies of the first 2 chars of # the original string where n is the length of the string. The string length will be >=2. # If input is "Wipro" then output should be "WiWiWiWiWi". string = input("enter the string: ") new_string = "" for i in range(len(string)): ne...
#Write a program to iterate over a dictionary using for loop and #print the keys alone, values alone and both keys and values. my_dict = {2: 20, 3: 30, 4: 40, 5: 50, 6: 60} keys = [] values = [] key_value = [] for key,value in my_dict.items(): keys.append(key) values.append(value) key_value.append({key:valu...
class MyStuff(object): def __init__(self,tangerine): print(tangerine) def apple(self): print("I AM CLASSY APPLES!") #instantiating an object alot like calling a function #giving all the functions in class to thing object(new empty object) #self is the empty object that python made for us #MyS...
#number = "113344422222" ### worst case(solution for this is line 20) #number = "12323434455345" ###normal case #number = "11111222223333344444" #### this works because it is already sorted number = "11111333334444422222" ###worst case for condition at line20 ### uncomment lines -- 8, 9 ,14 and commment line 15 fo...
#Write a program to sum all the values in a dictionary, considering the #values will be of int type. my_dict = {2: 30, 3: 40, 4: 50, 5: 60} print("existing dictionary:", my_dict) print("sum of all values:", sum(my_dict.values()))
#property decorator allows class Employee: def __init__(self, first, last): self.first = first self.last = last ## self.email = first + "." + last + "@email.com" # one solution is to define the email as a method instead of the attribute #but for this sol. we will have to change ea...
# Write a function to print the even numbers from a given list. List is passed to the function as an argument. # Sample List : [1, 2, 3, 4, 5, 6, 7, 8, 9] # Expected Result : [2, 4, 6, 8] def evens(list): even = [] for i in list: if i%2 == 0: even.append(i) else: contin...
# Write a program to accept the file name to be opened from the user, # if file exist print the contents of the file in title case or else handle # the exception and print an error message. file_name = input("enter the file name: ") try: with open(file_name, "r") as f: content = f.read() print(cont...
# HINTS TO FIND SECRET MESSAGE: # 1. THE NUMBER OF LINES TELLS ABOUT THE TIME OF MEETING # NOTE: 1 <= NUMBER OF LINES <= 24 # IF THE NUMBER OF LINES IS EXCEEDING 12, YOU NEED TO CONVERT IT TO 12 HRS. # FORMAT. # 2. THE WORD APPEARING FOR THE MAXIMUM NUMBER OF TIMES TELLS YOU THE MEETING PLACE. #...
# Write a program to add a key and value to a dictionary. # Sample Dictionary : {0: 10, 1: 20} # Expected Result : {0: 10, 1: 20, 2: 30} my_dict = {0: 10, 1:20} print("sample dictionary:", my_dict) my_dict[2] = 30 print("updated dictionary:", my_dict)
# Write a function that accepts a string and prints the number of upper case # letters and lower case letters in it. def count_s(string): upper = 0 lower = 0 for i in string: if i.islower(): lower += 1 elif i.isupper(): upper += 1 else: continue ...
# Write a program to accept two numbers from the user and perform division. # If any exception occurs, print an error message or else print the result. try: num1 = int(input("enter first number: ")) num2 = int(input("enter second number: ")) result = 0 result = num1/num2 except : print("Exception o...
# import bubblesort # import mergesort import sorting from DoubleLinkedList import * from random import randint max_numbers = 800 def random_list(count): numbers = DoubleLinkedList() # numbers.shift(2) # numbers.shift(1) # numbers.push(3) node = numbers.head for i in range(count, 0, -1): ...
import ctypes class ArrayList(object): """Custom implemenation of an 'array' backed list""" def __init__(self, capacity=1): self._size = 0 if capacity <= 0: capacity = 1 self._capacity = capacity self._storage = self._make_array(self._capacity) def __len__(self...