Question

In: Computer Science

PYTHON PROBLEM: TASKED TO FIND THE FLAW WITH THE FOLLOWING CODE: from itertools import count def...

PYTHON PROBLEM: TASKED TO FIND THE FLAW WITH THE FOLLOWING CODE:

from itertools import count

def take_e(n, gen):

    return [elem for (i, elem) in enumerate(gen) if i < n]

def take_zc(n, gen):

    return [elem for (i, elem) in zip(count(), gen) if i < n]

FIBONACCI UNBOUNDED:

def fibonacci_unbounded():

    """

    Unbounded Fibonacci numbers generator

    """

    (a, b) = (0, 1)

    while True:

        # return a

        yield a

        (a, b) = (b, a + b)

SUPPOSED TO RUN THIS TO ASSIST WITH FINDING THE FLAW:

take_e(5, fibonacci_unbounded())

Solutions

Expert Solution

The code under function fibonacci_unbounded is 100% correct.It will create and return a infinite fibonacci generator object.

FLAW:-

return [elem for (i, elem) in enumerate(gen()) if i < n]

          This is a normal list comprehension statment. The wrong   here is that a termination statement is not provided .

NO ,i<n will not terminate and return the list. It is a check condition for the values which has to inserted in list . It is not responsible for the termination and returning of the list. i<n will keep checking for the next element till infinity .

Same problem in the take_zc function

                       Thats why this code is not working.

REMEDY:- Replace your take_e function with this

             def take_e(n, gen):
                    l1 = []
                    for i,elem in enumerate(gen):
                          l1.append(elem)
                          if i>=n:return l1

Attaching the full code with output:-

     

NOTE :- Since , you haven't asked for take_zc function and I am not sure what this function want to achieve .It is difficult for me to write an alternative solution for that function.

        


Related Solutions

In Python The following code is intentionally done in poor style but runs as intended. def...
In Python The following code is intentionally done in poor style but runs as intended. def main(): c = 10 print("Welcome to Roderick's Chikkin and Gravy") e = False while not e: x = input("Would you like some chikkin?") if x == "Y" or x == "y": c = f(c) else: e = True if c == 0: e = True print("I hope you enjoyed your chikkin!") def f(c): if c > 0: print("Got you some chikkin! Enjoy") return c-1...
Python 3 Fix the code and rovide the correct indentation Code: import tkinter as tk from...
Python 3 Fix the code and rovide the correct indentation Code: import tkinter as tk from tkcalendar import DateEntry from openpyxl import load_workbook from tkinter import messagebox from datetime import datetime window = tk.Tk() window.title("daily logs") window.grid_columnconfigure(1,weight=1) window.grid_rowconfigure(1,weight=1) # labels tk.Label(window, text="Bar code").grid(row=0, sticky="W", pady=20, padx=20) tk.Label(window, text="Products failed").grid(row=1, sticky="W", pady=20, padx=20) tk.Label(window, text="Money Lost").grid(row=2, sticky="W", pady=20, padx=20) tk.Label(window, text="sold by").grid(row=3, sticky="W", pady=20, padx=20) tk.Label(window, text="Failed date").grid(row=4, sticky="W", pady=20, padx=20) # entries barcode = tk.Entry(window) product = tk.Entry(window) money =...
Python I am creating a class in python. Here is my code below: import csv import...
Python I am creating a class in python. Here is my code below: import csv import json population = list() with open('PopChange.csv', 'r') as p: reader = csv.reader(p) next(reader) for line in reader: population.append(obj.POP(line)) population.append(obj.POP(line)) class POP: """ Extract the data """ def __init__(self, line): self.data = line # get elements self.id = self.data[0].strip() self.geography = self.data[1].strip() self.targetGeoId = self.data[2].strip() self.targetGeoId2 = self.data[3].strip() self.popApr1 = self.data[4].strip() self.popJul1 = self.data[5].strip() self.changePop = self.data[6].strip() The problem is, I get an error saying:  ...
#Python 3.7 "Has no attribute" error - def get():     import datetime     d = date_time_obj.date()...
#Python 3.7 "Has no attribute" error - def get():     import datetime     d = date_time_obj.date()     return(d) print(a["Date"]) print("3/14/2012".get()) How to write the "get" function (without any imput), to convery the format ""3/14/2012" to the format "2012-03-14", by simply using "3/14/2012".get() ?
fix this code in python and show me the output. do not change the code import...
fix this code in python and show me the output. do not change the code import random #variables and constants MAX_ROLLS = 5 MAX_DICE_VAL = 6 #declare a list of roll types ROLLS_TYPES = [ "Junk" , "Pair" , "3 of a kind" , "5 of a kind" ] #set this to the value MAX_ROLLS pdice = [0,0,0,0,0] cdice = [0,0,0,0,0] #set this to the value MAX_DICE_VAL pdice = [0,0,0,0,0,0] cdice = [0,0,0,0,0,0] #INPUT - get the dice rolls i...
Please I seek assistance Python Programing import os import numpy as np def generate_assignment_data(expected_grade_file_path, std_dev, output_file_path):...
Please I seek assistance Python Programing import os import numpy as np def generate_assignment_data(expected_grade_file_path, std_dev, output_file_path): """ Retrieve list of students and their expected grade from file, generate a sampled test grade for each student drawn from a Gaussian distribution defined by the student expected grade as mean, and the given standard deviation. If the sample is higher than 100, re-sample. If the sample is lower than 0 or 5 standard deviations below mean, re-sample Write the list of student...
Please fix all the errors in this Python program. import math def solve(a, b, c): """...
Please fix all the errors in this Python program. import math def solve(a, b, c): """ Calculate solution to quadratic equation and return @param coefficients a,b,class @return either 2 roots, 1 root, or None """ #@TODO - Fix this code to handle special cases d = b ** 2 - 4 * a * c disc = math.sqrt(d) root1 = (-b + disc) / (2 * a) root2 = (-b - disc) / (2 * a) return root1, root2 if...
Code using R or Python We observe from our campus the temperature and count the number...
Code using R or Python We observe from our campus the temperature and count the number of squirrels. Our observations are T = [52, 52, 50, 54, 50, 52, 54, 80, 80] Sq = [8, 10, 6, 9, 6, 12, 12, 1, 0] a) What is the covariance of these vectors? (1point) b) What is the covariance matrix? (1point) c) What is the correlation coefficient? (1point) d) Find the coefficient of determination? (1point) e) Can you make any statement or...
Please convert this code written in Python to Java: import string import random #function to add...
Please convert this code written in Python to Java: import string import random #function to add letters def add_letters(number,phrase):    #variable to store encoded word    encode = ""       #for each letter in phrase    for s in phrase:        #adding each letter to encode        encode = encode + s        for i in range(number):            #adding specified number of random letters adding to encode            encode = encode +...
In Python Find the errors, debug the program, and then execute to show the output. def...
In Python Find the errors, debug the program, and then execute to show the output. def main():     Calories1 = input( "How many calories are in the first food?")     Calories2 = input( "How many calories are in the first food?")     showCalories(calories1, calories2)    def showCalories():     print('The total calories you ate today', format(calories1 + calories2,'.2f'))
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT