如何在控制台中显示数字,而无需for循环?

时间:2019-06-11 08:25:36

标签: javascript recursion numbers display

任务是创建一个递归,显示斐波那契数。我需要在控制台中显示斐波那契数字的数字链,而无(for)循环。

我对递归进行了优化,并使用(for)循环显示了数字。

def sentiment_scores(sentence): 

    local_tweet_sentiment_vader = []
    # Create a SentimentIntensityAnalyzer object. 
    sid_obj = SentimentIntensityAnalyzer() 

    # polarity_scores method of SentimentIntensityAnalyzer 
    # oject gives a sentiment dictionary. 
    # which contains pos, neg, neu, and compound scores. 
    sentiment_dict = sid_obj.polarity_scores(sentence) 
    print("Sentence Overall Rated As",end = " ") 

    # decide sentiment as positive, negative and neutral 
    if sentiment_dict['compound'] >= 0.05 : 
        print("Positive") 
        local_tweet_sentiment_vader.append("Positive")

    elif sentiment_dict['compound'] <= - 0.05 : 
        print("Negative") 
        local_tweet_sentiment_vader.append("Negative")
    else : 
        print("Neutral") 
        local_tweet_sentiment_vader.append("Neutral")
    return local_tweet_sentiment_vader

没有错误

1 个答案:

答案 0 :(得分:3)

此版本正在使用 while (非递归)

        "use strict";
        var arr = []
        let skkak = function(n)
        {
          if (n <= 1)
          {
            return n;
          }
          if(!isNaN(arr[n])){
            return arr[n];
          }

          else
          {
            let result = skkak(n - 1) + skkak(n - 2)
            arr[n] = result;
            return result;
          }
        }
       let i = 12;
       while(i > 0)
        {
          console.log(skkak(i));
          i--;
        }

递归方法

fibonacci = (n) =>
{
  if (n===1) 
  {
    return [0, 1];
  } 
  else 
  {
    let s = fibonacci(n - 1);
    s.push(s[s.length - 1] + s[s.length - 2]);
    return s;
  }
};

console.log(fibonacci(5)); // [0,1,1,2,3,5]