Primitive Calculator - Dynamic Approach

2024/9/8 10:43:49

I'm having some trouble getting the correct solution for the following problem:

Your goal is given a positive integer n, find the minimum number ofoperations needed to obtain the number n starting from the number 1.

More specifically the test case I have in the comments below.

 # Failed case #3/16: (Wrong answer)# got: 15 expected: 14# Input:# 96234## Your output:# 15# 1 2 4 5 10 11 22 66 198 594 1782 5346 16038 16039 32078 96234# Correct output:# 14# 1 3 9 10 11 22 66 198 594 1782 5346 16038 16039 32078 96234#  (Time used: 0.10/5.50, memory used: 8601600/134217728.)def optimal_sequence(n):sequence = []while n >= 1:sequence.append(n)if n % 3 == 0:n = n // 3optimal_sequence(n)elif n % 2 == 0:n = n // 2optimal_sequence(n)else:n = n - 1optimal_sequence(n)return reversed(sequence)input = sys.stdin.read()n = int(input)sequence = list(optimal_sequence(n))print(len(sequence) - 1)for x in sequence:print(x, end=' ')

It looks like I should be outputting 9 where I'm outputting 4 & 5 but I'm not sure why this isn't the case. What's the best way to troubleshoot this problem?

Answer

You are doing a greedy approach. When n == 10, you check and see if it's divisible by 2 assuming that's the best step, which is wrong in this case.

What you need to do is proper dynamic programming. v[x] will hold the minimum number of steps to get to result x.

def solve(n):v = [0]*(n+1)  # so that v[n] is therev[1] = 1  # length of the sequence to 1 is 1for i in range(1,n):if not v[i]: continueif v[i+1] == 0 or v[i+1] > v[i] + 1: v[i+1] = v[i] + 1# Similar for i*2 and i*3solution = []while n > 1:solution.append(n)if v[n-1] == v[n] - 1: n = n-1if n%2 == 0 and v[n//2] == v[n] -1: n = n//2# Likewise for n//3solution.append(1)return reverse(solution)
https://en.xdnf.cn/q/72573.html

Related Q&A

Cant pickle : attribute lookup builtin.function failed

Im getting the error below, the error only happens when I add delay to process_upload function, otherwise it works without a problem.Could someone explain what this error is, why its happening and any…

Pandas Merge two DataFrames without some columns

ContextIm trying to merge two big CSV files together.ProblemLets say Ive one Pandas DataFrame like the following...EntityNum foo ... ------------------------ 1001.01 100 1002.02 50 1003…

Getting Youtube data using Python

Im trying to learn how to analyze social media data available on the web and Im starting with Youtube.from apiclient.errors import HttpError from outh2client.tools import argparser from apiclient.disco…

matplotlib does not show legend in scatter plot

I am trying to work on a clustering problem for which I need to plot a scatter plot for my clusters.%matplotlib inline import matplotlib.pyplot as plt df = pd.merge(dataframe,actual_cluster) plt.scatte…

Correct usage of asyncio.Conditions wait_for() method

Im writing a project using Pythons asyncio module, and Id like to synchronize my tasks using its synchronization primitives. However, it doesnt seem to behave as Id expect.From the documentation, it se…

displaying newlines in the help message when using pythons optparse

Im using the optparse module for option/argument parsing. For backwards compatibility reasons, I cant use the argparse module. How can I format my epilog message so that newlines are preserved?In th…

How to use a learnable parameter in pytorch, constrained between 0 and 1?

I want to use a learnable parameter that only takes values between 0 and 1. How can I do this in pytorch? Currently I am using: self.beta = Parameter(torch.Tensor(1)) #initialize zeros(self.beta)But I…

generating a CSV file online on Google App Engine

I am using Google App Engine (python), I want my users to be able to download a CSV file generated using some data from the datastore (but I dont want them to download the whole thing, as I re-order th…

Python equivalence of Rs match() for indexing

So i essentially want to implement the equivalent of Rs match() function in Python, using Pandas dataframes - without using a for-loop. In R match() returns a vector of the positions of (first) matches…

Why doesnt Pydantic validate field assignments?

I want to use Pydantic to validate fields in my object, but it seems like validation only happens when I create an instance, but not when I later modify fields. from pydantic import BaseModel, validato…