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:
- Convert the input string into a list of integers.
- Check if the total number of elements matches the sum of the first
kpositive integers (since rowihasi+1elements). - Split the flat list into rows of increasing length (1 element for row 0, 2 for row 1, etc.).
- 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.
- The first row must be
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:
- 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. - 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.
- Type Conversion Oversights: You didn't convert input strings to integers early enough, leading to
str/intmismatches during arithmetic operations. - Flawed Validation Logic: The way you accessed
upper_leftandupper_rightelements 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
相关产品推荐
相关产品推荐

