text
stringlengths
37
1.41M
#how many fibonacci numbers to generate? fibo =int(input("how many fibonacci numbers to generate? ")) def fib(n): a,b=0,1 for i in range(0,fibo): print(a) a,b=b,b+a fib(fibo)
#!/usr/bin/python3 from operator import add, sub def a_plus_abs_b(a, b): # Return a+abs(b), but without calling abs. if b < 0: f = sub else: f = add return f(a,b) def two_of_three(a, b, c): """Return x*x + y*y, where x and y are the two largest members of the positive numbers a...
""" A board for Connect Four. Currently does not work for diagonal wins (e.g. 5 in a row along a diagonal). """ import numpy as np import random, time class Board(): # The idea is that you place your pieces at the top, and they # drop down to populate the first empty square closest to the bottom...
# A program that opens all .txt files in a folder and searches for any line that matches a user-supplied regular expression. # The results should be printed to the screen. import pyinputplus as pyip from pathlib import Path import os from posix import read import re def regexSearch(): # Ask user for his express...
from random import randint # 作业一 while True: a = randint(0, 100) if a == 66: print('找到66了') break else: print(a)
# 当前时间: 2021-09-06 12:28 # 会把整个模块的内容导入进来 import random print(random.randint(0,100)) # 导入某个方法 from random import randint,random print(randint(0,100)) import math print(math.sqrt(9)) print(math.sqrt(16)) import time time.sleep(2) print('hi') from time import sleep as s # 改名s s(2) print('python')
#!/usr/bin/env python3 import argparse import secrets def generate_password( total_passwords, total_characters, uppercase_threshold, number_threshold, punctuation_threshold): total_thresholds = ( uppercase_threshold + punctuation_threshold + number_threshold) pa...
#Bastien Anfray 8INF802 – Simulation de systèmes #Partie 3 - Utilisation du générateur import randomGen import pygame import time import sys import math import matplotlib.pyplot as plt #variables initialization steps = [] distArray = [] width = 700 height = 700 environment = [] arraytemp = [] userCho...
"""Core Common: Functions for use throughout the application""" # Python imports import re # Django imports from django.conf import settings # 3rd party apps # Local app imports # * Dictionary file location file_path = "%s/dictionary.txt" % (settings.STATIC_ROOT) def init_data(path) -> list: try: file...
from decimal import * class Order: """Orders represent the core piece of the exchange. Every bid/ask is an Order. Orders are doubly linked and have helper functions (next_order, prev_order) to help the exchange fulfill orders with quantities larger than a single existing Order. """ def __ini...
# Exercise: # * Create a login application, that can store and handle multiple users. # * The user should be asked if he wants to log in or create a login. # * If 'create': The users credentials should be written to a file # * If 'login': The users information should be checked agains the content of the file. # * The ...
class Cyclinder: def __init__(self,height,radius): self.height = height self.radius = radius def getHeight(self): return self.height def setHeight(self,height): if height > 0: self.height = height def getRadius(self): return self.radius def setRadius(self,radius): if ra...
def binary_to_dec(binary): sum = 0 valueOfdigit = len(binary) for i in binary: if i == "1" : sum += 2**(valueOfdigit-1) valueOfdigit -= 1 elif i == "0": valueOfdigit -= 1 return sum print(binary_to_dec("10010")) def dec_to_binary(decimal): binary = "" while decimal != 0 : ...
number = int(input("up to what number I check: ")) for i in range(2, number) : for divisor in range(2,i) : if i % divisor == 0 : break else: print(i)
#Write a Python program that asks the user how many Fibonacci numbers to generate and then displays them. howmanyFibo = int(input("How many Fibonacci do u want? ")) listOffibo = [1,1] if howmanyFibo == 1 : print(1) elif howmanyFibo == 0 : print("nothingg") elif howmanyFibo >=2 : for i in range(1, howmanyF...
x = int(input("Birinci Sayı:")) y = int(input("Ikinci Sayı:")) z = x + y print("Sayilarin Toplami:", z)
#● Write a Python program that determines and #prints whether a password is valid or not. #● A valid password is at least 8 characters long #and contains at least one uppercase letter #(A-Z), at least one lowercase letter (a-z), #and at least one number (0-9). password = str(input("enter the password: ")) upper = 0 l...
import unittest class MyUnitTest(unittest.TestCase): def test_splurthian(self): tests = [ ("Spenglerium", "Ee", True), ("Zeddemorium", "Zr", True), ("Venkmine", "Kn", True), ("Stantzon", "Zt", False), ("Melintzum", "Nn", False), ("Tul...
from random import randrange from re import match def insert_or_append(dictionary, key, value): if key not in dictionary: dictionary[key] = [value] else: dictionary[key].append(value) class Twister(object): def __init__(self, data_source="data.txt"): self.latin_to_gibberish = {} ...
import folium import pandas as pd # we require only these three fields from the dataset fields=['name_of_city','population_total','location'] data_frame=pd.read_csv("indian cities.csv",usecols=fields) #location column of data_frame consist of both latitude and longitude seperated by a ','. #seperate them into two col...
''' Challenge #5. Your challenge for today is to create a program which is password protected, and wont open unless the correct user and password is given. For extra credit, have the user and password in a seperate .txt file. for even more extra credit, break into your own program :) ''' import hashlib import os d...
# quy = ["nam", 77, "Vinh", 21, ["Anime", "Manga"]] # dictionary # CRUD #key : value person = { "name": "Quý", "age": 20, "university": "hust", "ex": 2, "favs": ["Anime", "Manga"], } key = "age" if key in person: print(person[key]) else: print("Not found") # for key in person.keys(): # ...
from random import * string = ["CHAMPION", "HERO", "SCHOOL", "SHOOT"] string = choice(string) work = list(string) updated_work = [] loop = True while loop: rand_work = choice(work) updated_work.append(rand_work) work.remove(rand_work) if len(work) == 0: loop = False print(*updated_work) ans =...
# 1. Sử dụng hàm type() # 2. Đặt tên biến sau đây thì lỗi # - Minh Quang (có dấu cách) # - 1quang (tên có số ở đầu) # - print (tên trùng hàm có sẵn) # Rad = int(input("Radius?")) # area = 3.14 * Rad # print("Area = ",area) from turtle import * shape("turtle") color("blue","yellow") speed(-1) begin_fill() #A square ...
Cel = int(input("Enter the temperature in celsius?")) Fah = Cel * 1.8 + 32 print(Cel, "=", Fah)
# load pandas for data preprocessing import pandas as pd # a class for Loading and preprocessing data class LoadData(object): def __init__(self, file_loc): self.file_loc = file_loc def __load_seperate_data(self): # load data using pd dataframe data = pd.read_csv(self.file_loc) ...
class Node(): """ [Class] Node A class to represent the Open Street Map Node. Properties: - osmId : Open Street Map ID. - lat : Latitude of this cell. - lon : Longitude of this cell. - isRoad : Boolean to mark whether this Node is a part of a road. - conn...
import re import copy # ##################### 定制插件(HTMl) ##################### class TextInput(object): """ 定制前端页面的标签: :return: <input type='text' class="c1" ID='I1' ..../>" """ def __init__(self,attrs=None): """ 标签自定制属性功能 :param attrs: {'class':'c1', .....} """ ...
debug = False with open("input.txt") as file: input = [line.strip() for line in file.readlines()] orbits = {} for connection in input: around, orbit = connection.split(")") orbits[orbit] = around count = 0 for orbit, around in orbits.items(): count += 1 # direct next = orbits.get(around) wh...
# https://www.hackerrank.com/contests/university-codesprint-2/challenges/breaking-best-and-worst-records n = int(input()) s = input().split() highest = int(s[0]) hcount = 0 least = int(s[0]) lcount = 0 s= s[1:] for i in s: if int(i) >highest: highest = int(i) hcount += 1 elif int(i) < least: least = int(i) lc...
##!/bin/python3 #https://www.hackerrank.com/contests/womens-codesprint-3/challenges/hackathon-shirts #https://www.hackerrank.com/contests/womens-codesprint-3/challenges/choosing-recipes import math import sys #sys.stdin = open("in","r") def hackathon_shirts(): t = int(input()) for case in range(t): n = int(inpu...
limit = 150000000 result = 0 def IsProbablePrime(num): for i in range(2, int(num/2)): remain = num % i if remain == 0: return False return True for i in range (10, limit, 10): squared = i * i; if squared % 3 != 1: continue if squared % 7 != 2 & squa...
import time def timing(f, n, a): print f.__name__, r = range(n) t1 = time.clock() for i in r: f(a); f(a); f(a); f(a); f(a); f(a); f(a); f(a); f(a); f(a) t2 = time.clock() print round(t2-t1, 3)
# Python program to print prime factors import math def primeFactors(n): # Print the number of two's that divide n dic = {} while n % 2 == 0: if 2 in dic: dic[2] += 1 else: dic[2] = 1 n = n / 2 # n must be odd at this point # so a ...
#https://www.hackerrank.com/challenges/pacman-bfs bfs #https://www.hackerrank.com/challenges/pacman-astar a* search #https://www.hackerrank.com/challenges/n-puzzle a* search def neighbors(edges, x,y): result = [] if x !=0: result.append((x-1,y)) if y != 0: result.append((x, y-1)) if y+...
#https://www.hackerrank.com/contests/w29/challenges/day-of-the-programmer y = int(input().strip()) if y == 1918: print( "26.09.1918") elif y<1918: if y %4 == 0: print( "12.09."+str(y)) else: print( "13.09."+str(y)) else: if (y %400==0) or (y%4==0 and y%100!=0): print( "12.09."+str(y)) else: print( "13.09....
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data """ MNIST is the machine learning "hello world" MNIST:Mixed National Institute of Standards and Technology database 数据库,存储各个国家地区,不同标准手写数字 """ """ MNIST data split three parts: 1.mnist.train:55000 data po...
#!/usr/bin/env python from time import sleep, time # Allows us to call the sleep function to slow down our loop import RPi.GPIO as GPIO # Allows us to call our GPIO pins and names it just GPIO GPIO.setmode(GPIO.BCM) # Set's GPIO pins to BCM GPIO numbering SW_PIN = 4 TX_PIN = 17 RX_PIN = ...
def add(a, b): return a + b def greeting(name, times): greeting_str = "" for _ in range(times): greeting_str += "Hi " + name + "\n" return greeting_str def return_values(a, b): return a * 2, b * 3, a * b def main(): x = add(2, 3) print(x) ret_str = greeting("Jonas", 3) p...
def my_func(*args): print("my_func with", len(args), "args") for value in args: print(value) def my_func_2(**kwargs): print("my_func_2 with", len(kwargs), "kwargs") print(type(kwargs)) print(kwargs) for k, v in kwargs.items(): print(k, "=", v) def my_func_3(*args, **kwargs):...
''' Created on Feb 1, 2018 @author: catad ''' from board.board import * ''' board = Board() b = board.setBoard() print(b) move = Square(1, 2, 1) s = Strategy(board) validator = Validate(board) game = Play(board, 0, s) control = MoveControl(game, validator) play = Play(board, 1, s) print(pla...
from flask.ext.sqlalchemy import SQLAlchemy db = SQLAlchemy() class Game(db.Model): """Board game.""" __tablename__ = "games" game_id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(20), nullable=False, unique=True) description = db.Column(db.String(100))...
""" If we calculate a2 mod 6 for 0 ≤ a ≤ 5 we get: 0,1,4,3,4,1. The largest value of a such that a2 ≡ a mod 6 is 4. Let's call M(n) the largest value of a &lt; n such that a2 ≡ a (mod n). So M(6) = 4. Find ∑M(n) for 1 ≤ n ≤ 107. """ import sympy def M(n): if sympy.isprime(n): return 1 for a in...
""" Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows: 21 22 23 24 25 20  7  8  9 10 19  6  1  2 11 18  5  4  3 1217 16 15 14 13 It can be verified that the sum of the numbers on the diagonals is 101. What is the sum of the numbers on the diagonals in a 10...
""" It turns out that 12 cm is the smallest length of wire that can be bent to form an integer sided right angle triangle in exactly one way, but there are many more examples. 12 cm: (3,4,5)24 cm: (6,8,10)30 cm: (5,12,13)36 cm: (9,12,15)40 cm: (8,15,17)48 cm: (12,16,20) In contrast, some lengths of wire, like 20 cm, c...
""" Take the number 192 and multiply it by each of 1, 2, and 3: 192 × 1 = 192 192 × 2 = 384 192 × 3 = 576 By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3) The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, ...
#python 3.7.2 """ Alternate Name: Annual Savings *compute annual dollar amount on savings invested at 10% over i_Years years variables: **i_Years = duration of investment **f_interest = interest ragte **f_iniInvest= initial investment output savings in last year (i_Years) """ import numpy as np #define variables i_Y...
palindrom_lst = [] for i in range(101, 999): print('i =',i) for j in range(i, 999): multi_IJ = str(i * j) # palindrom = multi_IJ[::-1]# print(i, '*', j, '=', str(i * j)) #print(palindrom) if palindrom == multi_IJ: palindrom=int(palindrom) p...
import matplotlib.pyplot as plt import numpy as np x = np.arange(0,2*np.pi,0.1) # start,stop,step y = np.sin(x) z = np.cos(x) plt.plot(x,y,x,z) tan_y = np.tan(x) plt.plot(x, tan_y) plt.legend(['sin(x)', 'cos(x)', 'tan(x)']) plt.title("Sin, Cosine, and Tangent One Period") plt.show()
age = int(input("Сколько тебе лет?\n")) if (age < 18 ): print("Тебе нет 18!") else: print("Проходи")
# Leader (Theory from Codility) # Uses python3 def slowLeader(A): # O(n^2) n = len(A) leader = -1 for k in range(n): candidate = A[k] count = 0 for i in range(n): if A[i] == candidate: count +=1 if count > n//2: leader = candidate return leader def fastLeader(A): # (n logn) ...
# Fibonacci # Uses python3 def fibonacci(n): if n < 3: return 1; else: return(fibonacci(n-1) + fibonacci (n-2)) # Example of usage if __name__ == "__main__": number = int(input("Enter fibonacci number: ")) result = list() for i in range(1,number+1): result.append(fibonacci(i)) print(result)
import random print("SIMPLE GAME OF SNAP!") print("===================="); #set loop condition to false snap = False #create array of cards deckOfCards = ["1","2","3","4","5","6","7","8","9","10","jack","queen","king"] lengthOfArray = len(deckOfCards) while snap==False: #get element from the ...
import math def length(x, y, a, b): return math.sqrt(pow(x - a, 2) + pow(y - b, 2)) class Thing: def __init__(self, x, y, keys): self.x = x self.y = y self.keys = keys def use(self, key, map): map.use_key(key) self.x = map.thing[0] self.y = map.thing[1] ...
class BST: # to initialize a BST, construct a node to be the root def __init__(self): self.root = None return # to create a new key-value pair # or to update a existed key-value pair def put(self, key, value): self.root = self.__putNode(self.root, key, value) return def __iter__(self): ...
def feq(str): s_list = str.split() unique_words = set(s_list) for words in unique_words: print('Frequency of ', words, 'is :',s_list.count(words)) str = 'I am a good boy and i am good in gaming and also in coding' freq(str)
from collections import defaultdict direction_deltas = { "<": (-1, 0), ">": (1, 0), "^": (0, 1), "v": (0, -1) } def take_turn(current_position, delivery_map, direction): current_position = tuple([sum(x) for x in zip(current_position, direction_deltas[direction])]) delivery_map[current_positio...
# fact = int(input("enter the nop. ")) # def fact(fact): # for i in range(1,fact): # fact = i*(i+1) # return fact # print(fact) # fact(8) def factorial(n): fac = 1 for i in range(n): fac = fac * (i +1) return fac num = int(input("enter the no. ")) print(factoria...
list = [6, 9, 70, 7, 44, ] for item in list: if item>6: print(item)
import random lst = ["snake", "water", "gun"] choice = random.choice(lst) print(" welcome t6o snake water gun game") inpt = str(input("choose between snake, gun and water: ")) if inpt=="snake" and choice == "water": print("opponent is water \n snake drunk the water") elif inpt == "snake" and choice == "gun"...
cgpa={} cgpa ["rafay"]=3.5 cgpa ["ali"]=2 cgpa ["khan"]=3.5 for k in cgpa.keys(): if(cgpa[k]<2.5 ): print("no degree's",k) else: print("degree awaded",k)
weather=int(input("enter your month ")) if weather<3 : print("winter") elif weather<6 : print("spring") elif weather<12 : print("summer")
#Q1 def number(): a=int(input("Enter 1st Number ")) b=int(input("Enter 2nd Number ")) print("Addition of two numbers is ",a+b) print("Subtraction of two numbers is ",a-b) print("Division of two numbers is ",a/b) print("Multiplication of two numbers is ",a*b) number() #Q2 print() ...
import sys if __name__ == "__main__": print("number args", len(sys.argv)) print("arguments", str(sys.argv)) user_input = [] is_input = False if len(sys.argv) == 7: is_input = True user_input= '[' for i in range(1,6): user_input += sys.argv[i] user_input += ', ' user_input += '1]' print(user_input...
# /usr/env/python # encoding:utf-8 import os import time from GameOfLife import GameOfLife clear = lambda: os.system('clear') def main(): clear() print("Game of Life") rows, cols = int(input("How many Rows:")), int(input("How many Columns:")) game = GameOfLife(rows, cols) while True: clea...
import webbrowser #open browsers import time #control time, like sleep import random #random ranges or numbers while True: randomSite=random.choice(['google.com','yahoo.com','bing.com','reddit.com']) #a list of sites that are going to be selected randomly and used as a value (string) only visit = "http://{}".format(...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def binaryTreePaths(self, root): """ Given a binary tree, return all root-to-leaf paths. 1 / \ ...
print("****************read****************") f3 = open("user.txt", "r") x= f3.read()# returns the string that contains file data print(type(x)) #print all print(x) f3.close()
# take size as input and perform the sum for the entered numbers s = 0 while (s < 100): num = int(input("enter num")) if (num > 0): s = num + s print("sum of num=", s) s = 0 while (s < 100): num = int(input("enter num")) if (num < 0): continue s = num + s print("sum of num=", s) ...
""" #how to take the inputs from the console # use input() function #by default input() funtn considers every value as string syntax: x = 90 #[value is provided by dev] x = input("enter num") # value provided from console/command prompt its is the dev responsibility to convert from string to any other data type: ...
import xlwt from xlwt import Workbook wb = Workbook() # add_sheet is used to create sheet. sheet1 = wb.add_sheet('Data') list = [ (10,20), (30,56) ] r=0 for row in list: c=0 for data in row: sheet1.write(r,c, data) c = c+1 r = r+1 wb.save('example2.xls') #This package is for w...
""" Req: Person has id, name, age as instance variables Employee has id, name, age, pan, pfNo as instance variables create obj and set data for person and employee. w/o inheritence ------------------------------------------ class Person: id=None name=None age=None def showPersonalInfo(self): ...
""" Write a function that prints welcome msg and call the function blocks: if if else elif for while function """ #write the function def myFunction(): print("Hello") print("Bye") #call the function myFunction() myFunction() myFunction()
""" Req: Perform div of two nums if the second num is zero then throw exception. and handle the exception """ def div(n1, n2): if n2 == 0: raise ArithmeticError("NUM2 cannot be zero") print(n1 / n2) try: div(6,2) div(6, 0) div(6, 3) except ArithmeticError as ex: print("issue due to "...
num1 = int(input("Enter num1")) num2 = int(input("Enter num2")) num3 = int(input("Enter num3")) if (num1 > num2): #big is between num1 and num3 if (num1 > num3): print("Big = ", num1) else: print("Big = ", num3) else: # big is between num2 and num3 if (num2 > num3): print("B...
#assignmnets a=b=c=100 print(a,b,c) a,b,c =100,200,300 print(a,b,c) a,b,c = 100, 12.2424, "krishna" print(a,b,c) print("***********print with seperator********************") a,b,c =100,200,300 print(a,b,c, sep ="$")# seperator for every value. default seperator is single space" " #what should be the printed after...
""" create a class with id, anme , age as instance variables. create obj , set data and display """ #create a class class Person: id=None age= None name=None def show(self): print("Hello") #create object p1 = Person() # set data p1.id = 90 p1.name="kumar" p1.age = 45 #dispaly print(p1.id)...
""" write a function that takes 2 nums as input and prints the bigger number. """ #how to write function def big(x,y): if(x>y): print("Big = ", x) else: print("Big = ", y) # x, y , bigger are the local variables #how to call the function big(30,13) n1=56 n2=90 big(n1,n2) n3= int(inp...
class PersonInfo: def __init__(self, pId, pName, pAge, pPan): self.__id = pId self.__name = pName self.__age = pAge self.pan = pPan #here id, name,age are private and pan is public def show(self): # public method ; can be callsed outside the class print(self.__id) ...
""" can we write try with multiple except blocks? Yes at a time only one except block is executed. For IndexError ,ZeroDivisionError ,ValueError we need to write 3 except blocks """ list = [1, 2, 3] x = 50 y = 0 age =None try: print(list[0]) print(list[7]) # trying to access 8th element but list has 4...
# Str is commonly data type # by defualt we have buildin strin operations name= "hi Accumed It technologies bye" # find length of string size = len(name) print("length of str==", size) #upper name="Hi How Are you" upStr = name.upper() # creates a new string #lower lowStr = name.lower() # creates a new string prin...
""" //take input for id , age , usertype //validate id & age , usertype //if id is positive print valid id , if not print invalid id //if age is greater than 18 print valid age else print invalid age //if usertype is "admin" print valid usertype else print invalid usertype if id is valid then only validate the age [ w...
from conn import getConn con =getConn() cursor = con.cursor() #fetch only id,name from all persons print("conn success") sql1 = "SELECT ID,NAME FROM person " cursor.execute(sql1) myresult = cursor.fetchall() for row in myresult: print(row) if cursor: cursor.close() if con: con.close()
""" one parent having multiple child classes. RBI is a parent class SBI , HDFC , ICICI are the child classes for RBI RBI: Parent class has - createAccount() - processLoan() SBI is a child of RBI - demat1() HDFC is a child of RBI - demat2() ICICI is a child of RBI - demat3() Creat...
""" while loop - every for loop can be converted to while loop print("***************************Print numbers from 1 for 50 ****************************************") for i in range(1,51): print(i) start with 1 print till< 51 and increment by 1 init is before the while loop condition is part of the while stat...
import xlwt from xlwt import Workbook #This package is for writing data and formatting information to older Excel files (ie: .xls # You’ll learn how to work with packages such as pandas, openpyxl, xlrd, xlutils and pyexcel. # Workbook is created wb = Workbook() # add_sheet is used to create sheet. sheet1 = wb.add_she...
# Pass by reference #write a function that takes obj as input arg def display(pObj): print(pObj.id) print(pObj.name) print(pObj.age) #write a function that returns person obj def getObj(id,name,age): pObj = Person() pObj.id = id pObj.name = name pObj.age = age return pObj def change(...
""" function that takes name as input and returns by appending Mr/Mrs """ def greet(name): res = "Mr/Mrs "+ name return res r1 = greet("murali") print(r1) r1 = greet("kumar") print(r1) r1 = greet("shyam") print(r1)
try: age = int ( input("enter age") ) print("after concerting age= ",age) except ValueError as ex: print("conversion not possible") print("end")
""" How to write the private function: --------------------------------------- - a private funtion should be written only inside the class - a private function cannot be accessed outside the class if we write "__" before the funtion name then the funtion will become private. ex: class Data: def show(self): ...
# Python code to sort the tuples using second element # of sublist Inplace way to sort using sort() def Sort(sub_li): # reverse = None (Sorts in Ascending order) # key is set to sort using second element of # sublist lambda has been used #While sorting via this method the actual content ...
""" Threading: ------------ -> concurrent programming/ parallel programming. -> by default single thread is created by python to run prog. -> test 1000 test cases on chrome , firefox , internet explorer. solution: threading. Threads: ------------------------ -threading is used for parallel programming. ...
x = 90 def process(): y = 89 print("process") class Person: # instance variables id = None name = None age = None # instance funtion # every instance function has self as default arg def show(self): print("hello inside show") """ here x is a global variable y is a lo...
# declaration of a set # will not allow duplicates # search by content is fast # insertion order is not maintained. # item #set for nums myset = {1, 45, 3,4,1, 1, 23, 0, -1 } print(myset) # creating a set using a constructor mySet6 = set() print(mySet6) #set for strings myset2 = {'sap', 'java', 'hana', 'sap', 'hado...
""" files: -------------- for working with files we need os module. create folder rename folder del folder create file del file write to file read from file file obj represents both file and folder. ex: import os """ import os import struct from os import path """ import os from os import path create a...
import os import os.path import struct from os import path #This function gives the name of the operating system dependent module imported. #The following names have currently been registered: �posix�, �nt�, �os2�, �ce�, �java� and �riscos� print(os.name) print(os.getcwd()) # For 32 bit it will return 32 and for 6...
""" var arg function: a function that takes any umber of arguments. sum of any numbers: """ #WRITE THE FUNCTION def sum(*nums): res =0 for n in nums: res= res + n print(res) #sum funtion can be called by passing any number of values #call the function sum(1,2) sum(1,2,24,2,5,21,36,25,343,7,25,7,2...
""" """ #code for returning value from the function def getData(): x = "Hello" return x #x is local varibles #call the function v1 = getData() print(v1) v2 = getData() print(v2)
#input : i/p func obj , return type: f2 obj """ outer functn : i/p: function obj ;; return :inner functn obj inner functn : i/p: NA , o/p: NA inner functn calls the functn using the function obj """ def f1(func): print("f1 is called") def f2(): print("f2 is called") func() re...
""" Req: Person: id,name Student : branch User : id,name , branch ,pan create obj for User , set data and display. Solution: -> Create Person class -> Create Student class -> Create User class with Person , Student as parent classes call show() method that should print every thing """ class Person: id=None n...