You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python验证用户输入是否为帕斯卡三角的代码问题排查

How to Validate a Flat Number Sequence as Pascal's Triangle

Let's break down how to solve this problem step by step, and fix the issues in your existing code.

The Core Approach

To validate if a flat sequence of numbers is a valid Pascal's Triangle, we need to:

  1. Convert the input string into a list of integers.
  2. Check if the total number of elements matches the sum of the first k positive integers (since row i has i+1 elements).
  3. Split the flat list into rows of increasing length (1 element for row 0, 2 for row 1, etc.).
  4. Verify each row follows Pascal's Triangle rules:
    • The first row must be [1].
    • Every subsequent row starts and ends with 1.
    • Each middle element is the sum of the two elements directly above it from the previous row.

Working Code Implementation

import math

def is_valid_pascal_triangle(values):
    # Convert input to list of integers (handle non-integer input)
    try:
        nums = list(map(int, values.split()))
    except ValueError:
        return False
    
    n = len(nums)
    # Calculate the number of rows k: solve k*(k+1)/2 = n
    discriminant = 1 + 8 * n
    sqrt_disc = math.isqrt(discriminant)
    
    # Check if discriminant is a perfect square and k is a positive integer
    if sqrt_disc * sqrt_disc != discriminant:
        return False
    k = (-1 + sqrt_disc) // 2
    if k <= 0 or k*(k+1)//2 != n:
        return False
    
    # Split the flat list into rows of increasing length
    rows = []
    index = 0
    for i in range(k):
        row_len = i + 1
        row = nums[index:index+row_len]
        rows.append(row)
        index += row_len
    
    # Validate the first row
    if rows[0] != [1]:
        return False
    
    # Validate all subsequent rows
    for i in range(1, k):
        current_row = rows[i]
        prev_row = rows[i-1]
        
        # Check first and last elements are 1
        if current_row[0] != 1 or current_row[-1] != 1:
            return False
        
        # Check middle elements are sum of the two elements above
        for j in range(1, len(current_row)-1):
            if current_row[j] != prev_row[j-1] + prev_row[j]:
                return False
    
    return True

# Get user input and run validation
user_input = input("Enter the numbers: ")
if is_valid_pascal_triangle(user_input):
    print("It is a pascal triangle")
else:
    print("It is not a pascal triangle")

Issues in Your Original Code

Let's go through why your code wasn't working:

  1. Incorrect Input Assumption: Your code took data[0] as the "size" of the triangle, but the input doesn't start with a size—it's just the sequence of numbers in the triangle rows.
  2. Unnecessary Grid Structure: You tried to build a padded 2D grid, which complicates validation logic. We don't need to pad rows with spaces; working directly with lists of integers is simpler and less error-prone.
  3. Type Conversion Oversights: You didn't convert input strings to integers early enough, leading to str/int mismatches during arithmetic operations.
  4. Flawed Validation Logic: The way you accessed upper_left and upper_right elements in the padded grid was incorrect, leading to wrong comparisons between elements.

Testing this code with your sample input 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 will correctly confirm it's a valid Pascal's Triangle.

内容的提问来源于stack exchange,提问作者random_student

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:13:28