## when predicate lambda

0 likes • Nov 19, 2022
Python

## More Python Posts

`# Python program for Plotting Fibonacci # spiral fractal using Turtle import turtle import math   def fiboPlot(n):     a = 0    b = 1    square_a = a     square_b = b       # Setting the colour of the plotting pen to blue     x.pencolor("blue")       # Drawing the first square     x.forward(b * factor)     x.left(90)     x.forward(b * factor)     x.left(90)     x.forward(b * factor)     x.left(90)     x.forward(b * factor)       # Proceeding in the Fibonacci Series     temp = square_b     square_b = square_b + square_a     square_a = temp           # Drawing the rest of the squares     for i in range(1, n):         x.backward(square_a * factor)         x.right(90)         x.forward(square_b * factor)         x.left(90)         x.forward(square_b * factor)         x.left(90)         x.forward(square_b * factor)           # Proceeding in the Fibonacci Series         temp = square_b         square_b = square_b + square_a         square_a = temp       # Bringing the pen to starting point of the spiral plot     x.penup()     x.setposition(factor, 0)     x.seth(0)     x.pendown()       # Setting the colour of the plotting pen to red     x.pencolor("red")       # Fibonacci Spiral Plot     x.left(90)     for i in range(n):         print(b)         fdwd = math.pi * b * factor / 2        fdwd /= 90        for j in range(90):             x.forward(fdwd)             x.left(1)         temp = a         a = b         b = temp + b     # Here 'factor' signifies the multiplicative  # factor which expands or shrinks the scale # of the plot by a certain factor. factor = 1  # Taking Input for the number of  # Iterations our Algorithm will run n = int(input('Enter the number of iterations (must be > 1): '))   # Plotting the Fibonacci Spiral Fractal  # and printing the corresponding Fibonacci Number if n > 0:     print("Fibonacci series for", n, "elements :")     x = turtle.Turtle()     x.speed(100)     fiboPlot(n)     turtle.done() else:     print("Number of iterations must be > 0")`
`def Fibonacci(n):     if n<0:         print("Incorrect input")     # First Fibonacci number is 0     elif n==1:         return 0    # Second Fibonacci number is 1     elif n==2:         return 1    else:         return Fibonacci(n-1)+Fibonacci(n-2)   # Driver Program   print(Fibonacci(9))`
`""" Currency Converter----------------------------------------"""import urllib.requestimport jsondef currency_converter(currency_from, currency_to, currency_input):    yql_base_url = "https://query.yahooapis.com/v1/public/yql"    yql_query = 'select%20*%20from%20yahoo.finance.xchange%20where%20pair' \                '%20in%20("'+currency_from+currency_to+'")'    yql_query_url = yql_base_url + "?q=" + yql_query + "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"    try:        yql_response = urllib.request.urlopen(yql_query_url)        try:            json_string = str(yql_response.read())            json_string = json_string[2:            json_string = json_string[:-1]            print(json_string)            yql_json = json.loads(json_string)            last_rate = yql_json['query']['results']['rate']['Rate']            currency_output = currency_input * float(last_rate)            return currency_output        except (ValueError, KeyError, TypeError):            print(yql_query_url)            return "JSON format error"    except IOError as e:        print(str(e))currency_input = 1#currency codes : http://en.wikipedia.org/wiki/ISO_4217currency_from = "USD"currency_to = "TRY"rate = currency_converter(currency_from, currency_to, currency_input)print(rate)`
```from collections import defaultdict
def collect_dictionary(obj):  inv_obj = defaultdict(list)  for key, value in obj.items():    inv_obj[value].append(key)  return dict(inv_obj)  ages = {  'Peter': 10,  'Isabel': 10,  'Anna': 9,}collect_dictionary(ages) # { 10: ['Peter', 'Isabel'], 9: ['Anna'] }```
```import osimport sysimport argparseimport jsonimport csvimport getpassimport stringimport randomimport re
from datetime import datetimeimport ldapimport requestsfrom requests.packages.urllib3.exceptions import InsecureRequestWarningrequests.packages.urllib3.disable_warnings(InsecureRequestWarning)from requests.auth import HTTPBasicAuthimport validators
import ipdb
# ldap functionsdef get_ldap_group_members(ldap_group, user, passwrd, DOMAIN, DOMAIN_SEARCH_BASE):    #DOMAIN_GROUP, DOMAIN_USER, DOMAIN_PASS, DOMAIN, DOMAIN_SEARCH_BASE    '''    Input a user name and search the directory    '''    #---- Setting up the Connection    #account used for binding - Avoid putting these in version control    bindDN = str(user)    bindPass = passwrd
#set some tuneables for the LDAP library.    ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW)    #ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, CACERTFILE)        conn = ldap.initialize('ldaps://'+str(DOMAIN))    conn.protocol_version = 3    conn.set_option(ldap.OPT_REFERRALS, 0)
#authenticate the connection so that you can make additional queries    try:        result = conn.simple_bind_s(bindDN, bindPass)     except ldap.INVALID_CREDENTIALS:        result = "Invalid credentials for %s" % user        sys.exit()
#build query in the form of (uid=user)    ldap_query = '(cn=' + ldap_group + ')'
query_result = []      lencount = True    range_start = 0    total_active_students_count = 0        while lencount:        #print(len(query_result))        range_end = range_start + 1499        member_range = ['member;range=' + str(range_start) + '-' + str(range_end)]        #print(member_range)        ldap_info = conn.search_s(str(DOMAIN_SEARCH_BASE), ldap.SCOPE_SUBTREE, filterstr=ldap_query, attrlist=member_range)        member_range = next(iter(ldap_info[0][1].keys()))        ldap_objects = ldap_info[0][1][member_range]        print("\n")        for ldap_object in ldap_objects:            decoded_member_string = ldap_object.decode("utf-8")            member_cn = re.split('=|,', decoded_member_string)[1]            print(f"User number: {total_active_students_count} in {ldap_group}: {member_cn}")            query_result.append(member_cn)            total_active_students_count = total_active_students_count + 1                if len(ldap_objects) == 1500:            lencount = True            range_start += 1500            range_end += 1500                else:            lencount = False            print(f"TOTAL USERS IN ActiveStudents: {total_active_students_count}")    return query_result

`""" Calculator----------------------------------------"""def addition ():    print("Addition")    n = float(input("Enter the number: "))    t = 0 //Total number enter    ans = 0    while n != 0:        ans = ans + n        t+=1        n = float(input("Enter another number (0 to calculate): "))    return [ans,t]def subtraction ():    print("Subtraction");    n = float(input("Enter the number: "))    t = 0 //Total number enter    sum = 0    while n != 0:        ans = ans - n        t+=1        n = float(input("Enter another number (0 to calculate): "))    return [ans,t]def multiplication ():    print("Multiplication")    n = float(input("Enter the number: "))    t = 0 //Total number enter    ans = 1    while n != 0:        ans = ans * n        t+=1        n = float(input("Enter another number (0 to calculate): "))    return [ans,t]def average():    an = []    an = addition()    t = an[1]    a = an[0]    ans = a / t    return [ans,t]// main...while True:    list = []    print(" My first python program!")    print(" Simple Calculator in python by Malik Umer Farooq")    print(" Enter 'a' for addition")    print(" Enter 's' for substraction")    print(" Enter 'm' for multiplication")    print(" Enter 'v' for average")    print(" Enter 'q' for quit")    c = input(" ")    if c != 'q':        if c == 'a':            list = addition()            print("Ans = ", list[0], " total inputs ",list[1])        elif c == 's':            list = subtraction()            print("Ans = ", list[0], " total inputs ",list[1])        elif c == 'm':            list = multiplication()            print("Ans = ", list[0], " total inputs ",list[1])        elif c == 'v':            list = average()            print("Ans = ", list[0], " total inputs ",list[1])        else:            print ("Sorry, invilid character")    else:        break`