Python:Roman Numeral to Int,搭乘C' C'计算

时间:2017-12-14 14:34:47

标签: python

我的代码不打印其中一个测试用例的正确数字 - " MCMXCVI"

应该打印:1996年。 它目前正在打印2106。

我怀疑它未能验证C' C'检查一个' M'我最后一个elif声明中的元素。但是,我输入正确,并且不知道为什么会这样。任何帮助将不胜感激!

编辑:所以我仍然无法弄明白。我知道它已经失败了" IV"和" MCM" - 但为什么?我正在解析所有内容而且它应该是 - 我绝对错过了一些东西。我需要一些n00b解释!

第二编辑:知道了!我跟踪了#34; IV"手工制作,超级慢慢地 - 我想出了我添加了V(5),我减去了1后,而不是添加5 - 1(4)。所以我最终得到了5.这个逻辑也失败了。我必须先检查元素的值,然后再添加。谢谢大家!

class Solution:
def romanToInt(self, roman):
    """
    :type s: str
    :rtype: int
    """
    sum = 0
    for element in range(0, len(roman)):
        if roman[element] == 'I':
            sum += 1

        elif roman[element] == 'V':
            sum += 5
            if roman[element - 1] == 'I':
                sum -= 1

        elif roman[element] == 'X':
            sum += 10
            if roman[element - 1] == 'I':
                sum -= 1

        elif roman[element] == 'C':
            sum += 100
            if roman[element - 1] =='X':
                sum -= 10

        elif roman[element] == 'L':
            sum += 50
            if roman[element - 1] == 'X':
                sum -= 10

        elif roman[element] == 'D':
            sum += 500
            if roman[element - 1] == 'C':
                sum -= 100

        elif roman[element] == 'M':
            sum += 1000
            if roman[element - 1] == 'C':
                sum -= 100

    return sum

1 个答案:

答案 0 :(得分:1)

由于没有普遍接受应该如何使用Roman numbers。例如。例如,来自维基百科的using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Threading; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Threading; namespace DarnContextMenu { // States used for filtering what is displayed via ICollectionView public enum EConState { Disabled, LoggedIn, LoggedOff }; // Stripped down model public class Connection { public Connection (string name) { Name = name; } public EConState State { get; set; } = EConState.Disabled; public string Name { get; set; } = string.Empty; } // Viewmodel public class ConnectionVM : DependencyObject, INotifyPropertyChanged { // Simulation of changing States static List<EConState> allStates = new List<EConState> { EConState.Disabled, EConState.LoggedIn, EConState.LoggedOff }; Timer t; void changeMe (object state) { if (state is ConnectionVM c) MainWindow.UIDispatcher .Invoke (() => c.State = allStates .Where (s => s != c.State) .OrderBy (_ => Guid.NewGuid ().GetHashCode ()) .First ()); } // End of simulation of changing States public static readonly DependencyProperty StateProperty = DependencyProperty.Register ("State", typeof (EConState), typeof (ConnectionVM), new PropertyMetadata (EConState.Disabled, (DependencyObject d, DependencyPropertyChangedEventArgs e) => { if (d is ConnectionVM vm) { vm.ConName = $"{vm.Connection.Name} [{(EConState)e.NewValue}]"; vm.PropertyChanged?.Invoke (vm, new PropertyChangedEventArgs (nameof (vm.State))); } })); // The state of the connection: influences if the connection is shown at all and used in sorting public EConState State { get { return (EConState)GetValue (StateProperty); } set { SetValue (StateProperty, value); } } // name created by models basename and state - changes via callback from StateProperty protected static readonly DependencyPropertyKey ConNamePropertyKey = DependencyProperty.RegisterReadOnly ("ConName", typeof (string), typeof (ConnectionVM), new PropertyMetadata ("")); public static readonly DependencyProperty ConNameProperty = ConNamePropertyKey.DependencyProperty; public string ConName { get { return (string)GetValue (ConNameProperty); } protected set { SetValue (ConNamePropertyKey, value); } } Connection Connection { get; } public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// /// </summary> /// <param name="connection">The connection - used for name and initial state</param> /// <param name="delay">a delay for the timer until the state-changes start</param> /// <param name="period">a delay between state changes </param> public ConnectionVM (Connection connection, TimeSpan delay, TimeSpan period) { t = new Timer (changeMe, this, (int)delay.TotalMilliseconds, (int)period.TotalMilliseconds); Connection = connection; State = Connection.State; // changing, simulated by timer inside VM } } public class MainViewModel { // all connections - in RL: occasionally new ones will be added by the user public ObservableCollection<ConnectionVM> Cons { get; set; } // filtered and sorted view on Cons - Collection public ICollectionView ConsView { get; set; } public MainViewModel (CollectionContainer cc) { // demodata - normally connections are created by userinteractions // this simulates 9 connections that change status every 4s to 10s Cons = new ObservableCollection<ConnectionVM> ( Enumerable.Range (1, 9) .Select (n => new ConnectionVM (new Connection ($"Connection #{n}") , TimeSpan.FromMilliseconds (300 * n) , TimeSpan.FromMilliseconds (700 * (n + 5)))) ); // create a sorted and filtered view // - sort by Status and then by Name // - show only Connecitons that are not Disabled ConsView = new CollectionViewSource { Source = Cons }.View; using (var def = ConsView.DeferRefresh ()) { ConsView.SortDescriptions.Add (new SortDescription ("State", ListSortDirection.Ascending)); ConsView.SortDescriptions.Add (new SortDescription ("ConName", ListSortDirection.Ascending)); ConsView.Filter = obj => (obj is ConnectionVM vm) && vm.State != EConState.Disabled; } // attach a Refresh-Action of MVM to each ConnectionVMs PropertyChanged which is fired by // ConnectionVM.StateProperty.Callback notifies each listener on StateProperty-Change foreach (var vm in Cons) { vm.PropertyChanged += (s, e) => // object s, PropertyChangedEventArgs e { cc.Collection = ConsView; RefreshViewModels (); }; } // in case the whole collection is added or removed to/from Cons.CollectionChanged += (s, e) => { cc.Collection = ConsView; RefreshViewModels (); }; } void RefreshViewModels () { ConsView.Refresh (); MainWindow.logger.Content = $"Valid: {Cons.Count (c => c.State != EConState.Disabled)}/{Cons.Count ()} (In/Off/Disabled: {Cons.Count (c => c.State == EConState.LoggedIn)} / {Cons.Count (c => c.State == EConState.LoggedOff)} / {Cons.Count (c => c.State == EConState.Disabled)})"; } } // create a MenuItem from the ConnectionVM - in real theres a bit more code inside due to Icons, Commands, etc. public class VmToMenuItemConverter : IValueConverter { public object Convert (object value, Type targetType, object parameter, CultureInfo culture) => new MenuItem { Header = (value as ConnectionVM).ConName ?? $"Invalid '{value.GetType ()}'" }; public object ConvertBack (object value, Type targetType, object parameter, CultureInfo culture) => null; } public partial class MainWindow : Window { public static Dispatcher UIDispatcher = null; public static Label logger = null; public MainWindow () { UIDispatcher = Application.Current.Dispatcher; InitializeComponent (); logger = msgBlock; DataContext = new MainViewModel (cc); } } } MCMX代表MDCCCCX,您应该检查每个数字的每个次要数字,而不仅仅是前一个数字。

我可以发表的评论是:

  • 例如,您应在1910中同时包含IV减法。而对于其他更大的数字也包括所有以前较小的数字。这适用于X添加LXV等。
  • 如果保持代码不变,则必须减去两倍的值,因为您已经添加了一次(在上一步中)。例如。 I将被评估为 + 1,+ 5,-1 = + 5 而不是+4。您需要 + 1,+ 5, -2 = + 5
  • 你应该检查你是否在第一个数字,IV然后element=0有不同的含义(最后一个数字),你不想检查它。

也许你的代码需要更多的bug修复,但这就是我找到的。