如何将列表中的每个元素提升至其对应索引的幂次?
Got it, let's solve this problem where we need to transform an input array by raising each element to the power of its index position (starting from 0). Here's how you can approach it in a couple of common programming languages:
Python Solution
You can use a clean list comprehension paired with enumerate()—this function lets you loop through the array while keeping track of both each element and its index.
def transform_array(arr): return [element ** index for index, element in enumerate(arr)] # Test with your examples print(transform_array([3, 2, 5])) # Output: [1, 2, 25] print(transform_array([5, 10, 20])) # Output: [1, 10, 400]
How it works
enumerate(arr)generates pairs like(0, 3),(1, 2),(2, 5)for the first test case.- For each pair, we calculate
element ** index(element raised to the index power). Since any number to the 0th power is 1, the first element will always be 1—perfect for your required output.
JavaScript Solution
In JavaScript, the map() method is ideal here. It lets you iterate over the array and modify each element using its index directly.
function transformArray(arr) { return arr.map((element, index) => Math.pow(element, index)); } // Test the examples console.log(transformArray([3, 2, 5])); // Output: [1, 2, 25] console.log(transformArray([5, 10, 20])); // Output: [1, 10, 400]
How it works
- The
map()callback receives both the current element and its index. Math.pow(element, index)handles the exponent calculation exactly as needed. Just like in Python, this will return 1 for the first element (since index 0 makes any non-zero number to the 0th power 1).
Quick Edge Case Note
If your input might have 0 as the first element, keep in mind that 0^0 is mathematically undefined, but most languages (including Python and JS) return 1 for this scenario, which matches your example pattern. If you need to handle this case differently, you can add a simple conditional check in the function.
内容的提问来源于stack exchange,提问作者ninepintcoggie

