Built-in Functions (1) Flashcards
#Built in functions #Write the arguments of slice()
slice(stop)
slice(start, stop, step)
Outcome of:
String =’GeeksforGeeks’
Gee
ek
s1 = slice(3)
s2 = slice(1, 5, 2)
print(String[s1])
print(String[s2])
#Built in functions #Write the arguments of .countOf()
Operator.countOf(freq = a, value = b)
Count frequency of 3
arr = [ 1, 2, 3, 3, 3 ]
from operator import *
arr = [ 1, 2, 3, 3, 3 ]
print(countOf(arr, 3))
#Built in functions #Write the arguments of copysign() and explain what it does
math.copysign(x, y)
Returns : float value consisting of magnitude from parameter x and the sign from parameter y.
Outcome of:
import math
math.copysign(-5,7)
5
#Built in functions # int.bit_length(), explain what it does
Returns the number of bits required to represent an integer in binary, excluding the sign and leading zeros.
Outcome of:
num = 7
print(num.bit_length())
3
#Built in functions #Write the arguments of isinstance() and explain what it does
isinstance(obj, class)
Returns : True, if object belongs to the given class/type if single class is passed or any of the class/type if tuple of class/type is passed, else returns False. Raises a TypeError if anything other than mentioned valid class type.
Check whether the object test=’stre’ belongs to the class integer
test=’stre’
isinstance(test, int)
Outcome:
False
Write the arguments of range()
range(start, stop, step)
Get this outcome using range():
[0, 2, 4, 6, 8]
list(range(0,10,2))
Write the arguments of set() and explain what it does
set(iterable)
Returns : An empty set if no element is passed. Non-repeating element iterable modified as passed as argument.
Code
lis1 = [ 3, 4, 1, 4, 5 ]
{1, 3, 4, 5}
set(lis1)
Parameters of hash(obj) and explain what it does
obj : The object which we need to convert into hash.
Returns : Returns the hashed value if possible.
Outcome of:
lis1 = [1, 2, 3, 4, 5]
lis1 = iter(lis1)
next(lis1)
Once the iteration is complete, it raises a StopIteration exception and iteration count cannot be
reassigned to 0.
herefore, it can be used to traverse the container just once.
Arguments of iter() and explain limitations
iter(obj, sentinel)
obj : Object which has to be converted to iterable ( usually an iterator ).
sentinel : value used to represent end of sequence.
Once the iteration is complete, it raises a StopIteration exception and iteration count cannot be
reassigned to 0.
Complete code
class GfG : name = "GeeksforGeeks" age = 24
…= GfG
…(obj,’name’)
Outcome:
‘GeeksforGeeks’
class GfG : name = "GeeksforGeeks" age = 24
obj = GfG
getattr(obj,’name’)
Explain random.sample() function
Syntax : random.sample(sequence, k)
Parameters:
sequence: Can be a list, tuple, string, or set.
k: An Integer value, it specify the length of a sample.
random sampling without replacement.
Get a sample of three numbers from a list called list1
from random import sample
list1 = [1, 2, 3, 4, 5]
sample(list1,3)
Outcome:
[2, 3, 4]
Finish code
from collections import …
x = …(“geeksforgeeks”)
Outcome:
g g e e e e k k s s f o r
from collections import Counter
x = Counter(“geeksforgeeks”)
for i in x.elements():
print ( i, end = “ “)
Code to get:
bytearray(b’Geeksforgeeks’)
str = “Geeksforgeeks”
array1 = bytearray(str, ‘utf-8’)
print(array1)
standard deviation of list1.
import statistics
# creating a simple data - set list1 = [1, 2, 3, 4, 5]
Get the standard deviation
list1=list(range(1,8))
#Outcome: 2.16
round(statistics.stdev(list1),2)
Calculate the median of :
list1=np.linspace(0,2,11)
import statistics
import numpy as np
list1=np.linspace(0,2,11)
statistics.median(list1)
Outcome:
1.0
Get the mode
data1 = (2, 3, 3, 4, 5, 5, 5, 5, 6, 6, 6, 7)
from statistics import mode
mode(data1)
Outcome:
5
Print each letter in the same line with one second of difference
strn = “GeeksforGeeks”
import time
for i in range(0, len(strn)):
print(strn[i], end =””)
time.sleep(2)
Get the complete current time
e.g. 2020-04-25 14:47:50.957890
current_time = datetime.datetime.now()
print(current_time)
Complete the code
str = “This article is written …”
print (…(“Python”))
#Outcome: This article is written in Python
str = “This article is written in {}”
print (str.format(“Python”))
#Complete the code …. # Function which generates a new # random number everytime it executes def generator(): ...(1, 10)
from random import randint
def generator(): return randint(1, 10)
Complete the code
a = {‘x’:’John’, ‘y’:’Wick’}
…
#Outcome: John's last name is Wick
print(“{x}’s last name is {y}”.format_map(a))
Split the word using @ as separator only once
word = ‘geeks@for@geeks’
#Outcome: ['geeks@for', 'geeks']
print(word.rsplit(‘@’, 1))
Remove ‘b’
list2 = [ ‘a’, ‘b’, ‘c’, ‘d’ ]
#Outcome: ['a', 'c', 'd']
list2.remove(‘b’)
print(list2)
Code
string = ‘ Geeks for Geeks ‘
#Outcome: print(string.strip())
string = ‘ Geeks for Geeks ‘
# Leading spaces are removed print(string.strip())
Outcome of :
string = ‘ Geeks for Geeks ‘
print(string.strip(‘Geeks’))
Geeks for Geeks
#To remove Geeks should be: print(string.strip(' Geeks')) #The function returns another string with both leading and trailing characters being stripped off.
Get the factor of this list
seq = [0, 1, 2, 3, 5, 8, 13]
#Outcome: [0, 2, 8]
result = filter(lambda x: x % 2 == 0, seq)
print(list(result))
Get all the permutations for:
s = “GEEK”
#Outcome GEEK GEKE GKEE EGEK EGKE EEGK EEKG EKGE EKEG KGEE KEGE KEEG
from itertools import permutations
s = "GEEK" p = permutations(s)
d = [] for i in list(p): if (i not in d): d.append(i) print(''.join(i))