Trending March 2024 # Python Program To Search An Element In An Array # Suggested April 2024 # Top 11 Popular

You are reading the article Python Program To Search An Element In An Array updated in March 2024 on the website Cattuongwedding.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested April 2024 Python Program To Search An Element In An Array

In Python, there are mainly two searching algorithms that are majorly used. Out of those, the first one is Linear Search and the second one is Binary Search.

These two techniques are majorly used in order to search an element from the given array or from the given list also. While searching an element, there are two methodologies that can be followed in any kind of algorithm. One of those is recursive approach and the other is iterative approach. Let us discuss both algorithms in both approaches and solve similar problems.

Linear Search

The Linear Search technique is also known as Sequential search. The meaning of the name “ Sequential search ” is definitely justified by the process followed by this search algorithm. It is a method or technique which is used in order to find the elements within an array or a list in Python.

It is known to be the most simplest and easiest of all the other searching algorithms. But, the only drawback of this algorithm is that it is not so efficient. That is the main reason for not using Linear search very frequently.

Algorithm

Step 1 − It searches for an element in a sequential order just by comparing the desired element with each element present in the given array.

Step 2 − If the desired element is found, then the index or position of the element will be displayed to the user.

Step 3 − If the element is not present within the array, then the user will be informed that the element is not found. In this way, the algorithm is processed.

In general, Linear search algorithm is comparatively suitable and efficient for small arrays or small lists which has a size less than or equal to 100 as it checks and compares with each element.

More time will be consumed if the desired element is present in the last position of the array.

The Time complexity of Linear Search algorithm in best case is “ O( 1 ) ”. In this case, the element will be present in the first position of the array, i.e., with the index “ 0 ”.

The Time complexity of Linear Search algorithm in average case is “ O( n ) ”. In this case, the element will be present in the middle position of the array, i.e., with the index “ ( n – 1 ) / 2 ” or “ (( n – 1 ) / 2 )+ 1 ”.

The Time complexity of Linear Search algorithm in worst case is “ O( n ) ”. In this case, the element will be present in the last position of the array, i.e., with the index “ n-1 ”.

Example

In the following example, we are going to learn about the process of searching an element in an array using Linear search.

def iterative_linear( arr, n, key_element): for x in range(n): if(arr[x] == key_element): return x return -1 arr = [2, 3, 5, 7, 9, 1, 4, 6, 8, 10] max_size = len(arr) key = 8 result = iterative_linear(arr, max_size - 1, key) if result != -1: print ("The element", key," is found at the index " ,(result), "and in the ", (result+1), "position") else: print ("The element %d is not present in the given array" %(key)) Output

The output for the above program is as follows −

The element 8  is found at the index  8 and in the  9 position Example (Recursive)

In the following example, we are going to learn about the process of searching an element in an array using Linear search in recursive approach.

def recursive_linear( arr, first_index, last_index, key_element): if last_index < first_index: return -1 if arr[first_index] == key_element: return first_index if arr[last_index] == key_element: return last_index return recursive_linear(arr, first_index + 1, last_index - 1, key_element) arr = [2, 3, 5, 7, 9, 1, 4, 6, 8, 10] max_size = len(arr) key = 8 result = recursive_linear(arr, 0, max_size - 1, key) if result != -1: print ("The element", key," is found at the index " ,(result), "and in the ", (result+1), "position") else: print ("The element %d is not present in the given array" %(key)) Output

The output for the above program is as follows −

The element 8  is found at the index  8 and in the  9 position Binary Search

The Binary search algorithm is quite different from the Linear search algorithm. It follows completely different procedure in order to search an element from the array. It only considers sorted arrays generally.

If the array is not sorted in some cases, the array is sorted and then the procedure of the Binary search algorithm starts. As soon as the array is considered by the Binary search algorithm, it is sorted first and then the algorithm is applied on the array.

Algorithm

Step 1 − The process of sorting the array is the first step followed.

Step 2 − After the array is sorted, the array is considered as two halves. One half is starting from the first element to the middle element of the sorted array and the second half is starting from the element after the middle element to the last element of the sorted array.

Step 3 − The key element (the element that is supposed to be searched is known as key element) is compared with the middle element of the sorted array.

Step 4 − If the key element is less than or equal to the middle element of the sorted array, the second half elements are ignored further as the key element is smaller than the middle element. So, definitely, the element must be present in between the first element and the middle element.

Step 6 − If the key element is greater than the middle element, then the first half of the sorted array is ignored and the elements from the middle element to the last element are considered.

Step 7 − Out of those elements, the key element is again compared with the middle element of the halved array and repeats the same procedure. If the key element is greater than the middle element of the halved array, then the first half is neglected.

Step 8 − If the key element is less than or equal to the middle element of the halved array, the second half of the halved array will be neglected. In this way, the elements are searched in any half of the array accordingly.

So, when compared to the Linear search, the complexity is reduced by half or more than half as half of the elements will be removed or not considered in the first step itself. The best case time complexity of Binary search is “ O(1) ”. The worst case time complexity of Binary search is “ O(logn) ”. This is how the algorithm of binary search works out. Let us consider an example and apply the Binary search algorithm to find out the key element out of the elements present in the array.

Example

In this example, we are going to learn about the process of searching an element in an array using Binary search in recursive approach.

def recursive_binary(arr, first, last, key_element): if first <= last: mid = (first + last) if arr[mid] == key_element: return mid return recursive_binary(arr, first, mid - 1, key_element) elif arr[mid] < key_element: return recursive_binary(arr, mid + 1, last, key_element) else: return -1 arr = [20, 40, 60, 80, 100] key = 80 max_size = len(arr) result = recursive_binary(arr, 0, max_size - 1, key) if result != -1: print("The element", key, "is present at index", (result), "in the position", (result + 1)) else: print("The element is not present in the array") Output

The output for the above program is as follows −

The element 80  is found at the index 3 and in the position 4 Example

In this example, we are going to learn about the process of searching an element in an array using Binary search in iterative approach.

def iterative_binary(arr, last, key_element): first = 0 mid = 0 while first <= last: mid = (first + last) if arr[mid] < key_element: first = mid + 1 last = mid - 1 else: return mid return -1 arr = [20, 40, 60, 80, 100] key = 80 max_size = len(arr) result = iterative_binary(arr, max_size - 1, key) if result != -1: print("The element", key, "is present at index", (result), "in the position", (result + 1)) else: print("The element is not present in the array") Output

The output for the above program is as follows −

The element 80  is found at the index 3 and in the position 4

You're reading Python Program To Search An Element In An Array

Swift Program To Fill An Array With A Specific Element

In this article, we will learn how to write a swift program to fill an array with a specific element.

An array is used to store elements of same data type in an order whereas a set is used to store distinct elements of same data type without any definite order. In an array, every element has an index. The array index is start from 0 and goes up to N-1. Here N represent the total number of array elements.

We can fill an array with a specified element using the following methods −

Using user defined function

Using array initialisation

Using map() function

Using indices property

Method 1: Using user-defined Function

To fill the given array with a specified element we create a function in which we run a for loop to iterate through each element of the given array and assign the specified element to each element of the given array.

Example

Following Swift program to fill an array with a specific element.

import Foundation import Glibc for i in 0..<arr.count { arr[i] = element } } var arr = [34, 5, 7, 78, 2, 11, 67, 8] print("Original Array:", arr) fillArray(arr: &arr, with: 1) print("Modified Array:", arr) Output Original Array: [34, 5, 7, 78, 2, 11, 67, 8] Modified Array: [1, 1, 1, 1, 1, 1, 1, 1]

Here in the above code, we have an array of integer type. Now we create a function to fill the array with the specified element that is 1. So in this function, we run a for loop to iterate through each element of the given array and assign the element with the specified value that is 1.

Method 2: Using Array Initializer

We can also use array initializer to create an array the is filled with a specified element.

Syntax Array(repeating: Value, Count:Value)

Here, repeating parameter specifies the element to be repeated and the count parameter specifies the number of the times element should be repeated.

Example

Following Swift program to fill an array with a specific element.

import Foundation import Glibc let ele = "Pink" let countVal = 6 let mArray = Array(repeating: ele, count: countVal) print("Array is:", mArray) Output Array is: ["Pink", "Pink", "Pink", "Pink", "Pink", "Pink"]

Here in the above code, we create an array using Array() initializer and inside this Array initialiser we pass the value of repeating and count parameter. Now this array() initializer fill the given array with “Pink” element and repeat this element 6 times.

Method 3: Using map(_:) function

We can also fill an array with a specified element using map(_:) function. The map(_:) function is used to return an array containing the results of mapping the given closure over the array’s elements.

Syntax

>[T]

Here, t is a mapping closure. It takes an element of the given array as its parameter and return a transformed value of the same or different type.

Example

Following Swift program to fill an array with a specific element.

import Foundation import Glibc var myArr = [3, 5, 6, 7, 3, 3, 2, 3, 2] print("Original Array:", myArr) myArr = chúng tôi { _ in 9 } print("Modified Array:", myArr) Output Original Array: [3, 5, 6, 7, 3, 3, 2, 3, 2] Modified Array: [9, 9, 9, 9, 9, 9, 9, 9, 9]

Here in the above code, we create an array of integer type. Now using map() function we fill the given array elements with 9. So to do this we pass a closure { _ in 9 } in the map() function and then map() function will fill each element of the given array with element 9.

Method 4: Using Indices Property

To fill the given array with a specified element we can use indices property of the array.

Example

Following Swift program to fill an array with a specific element.

import Foundation import Glibc var number = [Int](repeating: 0, count: 5) let element = 10 for x in number.indices { number[x] = element } print("Array:", number) Output Array: [10, 10, 10, 10, 10]

Here in the above code, we declare an array with 5 element. Now we run a for loops to iterate over the indices property of the array and assign the value of the element = 10 variable to each index.

Conclusion

Therefore, this is how we can fill an array with a specified element. Here, always remember the element type is equal to the array type.

Java Program For Minimum Product Subset Of An Array

Array is a linear data structure that is used to store a group of elements with similar datatypes. It stores data in a sequential manner. Once we create an array we can’t change its size i.e. it is of fixed length.

The problem statement states that for a given array we have to find the minimum product of its subset. In this article, we will try to find the solution to the given problem.

Program for minimum product of subsets Example 1

Let’s try to understand the problem and possible solution through an example.

For the above array a few possible subsets could be −

Now, we will compute their products and return the minimum of them. Here, 5 is the minimum.

Syntax for Array Data_Type[] nameOfarray; Or, Data_Type nameOfarray[]; Or, Data_Type nameOfarray[] = new Data_Type[ sizeofarray ]; Data_Type nameOfarray[] = { values separated with comma };

We can use any of the above syntaxes in our program.

Algorithm

Step 1 − We begin by importing the ‘java.lang.Math’ package so that we can use method ‘min()’ of the class ‘Math’ to check the minimum value among two given arguments.

Step 2 − Now, create a class ‘Subset’ and inside it defines a method named ‘minProduct()’ along with an array as a parameter.

Step 3 − Inside the method ‘minProduct()’, declare and initialize an integer variable named ‘res’ to store the sum of product of subsets. Moving further, take a for loop that will run till the length of the array.

Step 4 − We will declare and initialize another integer variable named ‘prod’ to store the product of subsets during each iteration.

Step 5 −Now, define another for loop inside the first one that will run from ‘i + 1’ to length of array. During each iteration, it will check the minimum among sum of product and product of subsets.

Step 6 − At the end, in the main() method, we will declare and initialize two arrays of type integer to find their minimum product of subsets. Moving ahead create an object named ‘obj’ of class ‘Subset’ and use this object to call the method ‘minProduct()’ with argument.

Example import java.lang.Math; class Subset { void minProduct(int aray[]) { int res = aray[0]; for (int i = 0; i < aray.length; i++) { int prod = aray[i]; for (int j = i + 1; j < aray.length; j++) { res = Math.min(res, prod); prod = prod * aray[j]; } res = Math.min(res, prod); } System.out.println("Minimum product of Sub array is: " + res); } } public class Minsub { public static void main(String[] args) { int aray1[] = { 4, -6, 3, 6}; int aray2[] = { 3, 5, 9, 7, 12, 30 }; Subset obj = new Subset(); obj.minProduct(aray1); obj.minProduct(aray2); } } Output Minimum product of Sub array is: -432 Minimum product of Sub array is: 3 Conclusion

We have discussed the solution for how we can find the minimum product of subsets of a given array. Also, we discovered the syntax to declare and initialize an array. We have used a static method ‘min()’ that checks minimum of two specified values. Remember one thing about static methods they can be called without creating any object, we just use the class name with the dot operator (.).

How To Get The Sign Of An Integer In Python?

Introduction

Python Integers are one of the primary data types, and are used for almost all major mathematical and logical operations. In Python, integers are zero,positive or negative whole numbers without a fractional part and having unlimited chúng tôi can be expressed in binary, octal and hexadecimal values. In this article, we will learn how to obtain the sign of an integer.

Methods Used

Using simple mathematical comparison with zero

Using copysign() function of math module

Using numpy.sign() function

Creating a method with abs() function

Method 1: Using Mathematical Comparison with Zero

We can use the basic mathematical definition of positive and negative numbers to find the sign of a given integer. We use a basic if-else structure to determine the sign of a number.

Syntax

else if number<0 return -1 else return 0

In this method, we use a cascaded if-else-if structure to create a decisionmaking point at the point zero in the number line of integers. If the number input by the user is greater than zero, the program returns +1, if it is less than zero, the program returns -1 and if it’s zero, the program returns zero as the answer.

Algorithm

Step 1 − Take the user input for the integer for which sign is to be determined

Step 2 − Create an ‘if’ with the initial condition that if the input number is greater than zero, the function returns 1

Step 3 − Create a cascading ‘else-if’ condition which returns -1 if the input number is less than zero

Step 4 − Create a final ‘else’ condition where the function returns zero if the input number is zero

Example def solution(number): return 1 elif (number<0): return -1 else: return 0 val =-2 sol = solution(val) print(sol) Output -1 Method 2: Using copysign() Function of Math Module

The copysign() function in the math module returns the value of the first argument with the sign of the second argument. Hence we use 1 in place of the first argument to find the sign of the input integer placed as the second argument. This function can handle values of integers,floating point numbers as well as positive and negative nan.

Syntax return copysign(1,number)

To perform this operation, we need to call the copysign function. As arguments, we need to pass two numbers, from which the magnitude of the first number and the sign of the second number is returned by the function as a single number.

Algorithm

Step 1 − Import the math module

Step 2 − Take the input integer from the user for which sign is to be determined

Step 3 − Pass the integer as the second argument in the copysign() function, according to the given syntax

Example import math def solution(number): return int(math.copysign(1,number)) val = -2 sol = solution(val) print(sol) Output -1 Method 3: Using numpy.sign() Function

The numpy module provides a sign() function which can be used to determine the sign of an integer. This is pretty useful as there isn’t any sign() function by default in the math library of Python. It can be used on an entire array of integers to display the sign element-wise.

Syntax numpy.sign(array [], out)

The syntax is pretty simple, it calls the sign function and passes two arguments. Only the first argument is compulsory, the second one is chúng tôi first argument passes the array of elements, the second argument is output array placed with the result.

Algorithm

Step 1 − Import the numpy module

Step 2 − Take input elements in the array for which sign(s) are required to be determined

Step 3 − Call the sign() function and pass the array containing the target elements

Step 4 − Display the output values i.e. the signs of the integers

Example import numpy as user #importing numpy array=[25, -25, 0] #input array print("input array : ", array) #input array with elements print("Check sign of array : ", user.sign(array)) #signs of elements Output input array: [25 -25 0] Check sign of array: [1 -1 0] Method 4: Creating a Method with abs() Function

We can use the abs() function to define a sign function which returns the sign of the integer. The abs() function returns the absolute value of a number.

Syntax return x/abs(x)

Here we divide the integer with its absolute value to find the sign of the integer. As we divide two integers here, the function returns a float value, however it works for integers.

Algorithm

Step 1 − Define a function

Step 2 − Pass the number to the function whose sign is to be determined as an argument

Step 3 − Create an ‘if-else’ structure to check if input integer is zero

Step 4 − Display the output value by dividing the integer with its absolute value

Example def int_sign(x): if (x==0): return 0 else: return x/abs(x) num=-2 print(int_sign(num)) Output -1.0 Conclusion

In this article, we have talked about some ways in which we can find the sign of an integer supplied by the user or set in the program. This article is usually written keeping Python in mind, however similar methods are also available in different programming languages.

An Introduction To Python For Seo Pros Using Spreadsheets

2024 far exceeded my expectations in terms of Python adoption within the SEO community.

As we start a new year and I hear more SEO professionals wanting to join in the fun, but frustrated by the initial learning curve, I decided to write this introductory piece with the goal of getting more people involved and contributing.

When you implement the same workflow in Python, you can trivially reproduce the work or even automate the whole workflow.

We are going to learn Python basics while studying code John Mueller recently shared on Twitter that populates Google Sheets. We will modify his code to add a simple visualization.

— 🍌 John 🍌 (@JohnMu) January 3, 2023

Setting up the Python Environment

Similar to working with Excel or Google Sheets, you have two primary options when working with Python.

You can install and run Python on your local computer, or you can run it in the cloud using Google Colab or Jupyter notebooks.

Let’s review each one.

Working with Python on Your Local Computer

I typically choose to work on my Mac when there is software that won’t run in the cloud, for example, when I need to automate a web browser.

You need to download three software packages:

Anaconda.

Visual Studio Code.

The Python bindings for Code.

This will take a while to complete.

Once done, search for the Anaconda Navigator and launch it.

You can think of this notebook as similar to a new Excel sheet.

The next step is optional.

I personally use Visual Studio Code when I need to write code in Python and JavaScript or when writing JavaScript code. You can also use it if you want to convert your notebook code into a command-line script.

It is easier to prototype in Jupyter notebooks and when you get everything to work, you can use Visual Studio Code to put everything together in a script or app that others can use from the command line.

Make sure to install the Python extension for VSC. You can find it here.

Visual Studio Code has built-in support for Jupyter Notebooks.

You can create one by typing the keyword combination Command+Shift+P and selecting the option “Python Jupyter Notebook”.

Working with Python in the Cloud

I do most of my Python work on Google Colab notebooks so this is my preferred option.

Learning the basics of Python & Pandas

Mueller shared a Colab notebook that pulls data from Wikipedia and populates a Google Sheet with that data.

Professional programmers need to learn the ins and out of a programming language and that can take a lot of time and effort.

For SEO practitioners, I think a simpler approach that involves studying and adapting existing code, could work better. Please share your feedback if you try this and see if I am right.

We are going to review most of the same basics you learn in typical Python programming tutorials, but with a practical context in mind.

Let’s start by saving Mueller’s notebook to your Google Drive.

Here is the example Google sheet with the output of the notebook.

Overall Workflow

Mueller wants to get topic ideas that perform better in mobile compared to desktop.

— 🍌 John 🍌 (@JohnMu) December 30, 2023

He learned that celebrity, entertainment, and medical content does best on mobile.

We have several pieces to the puzzle.

An empty Google sheet with 6 prefilled columns and 7 columns that need to be filled in

The empty Google sheet includes a Pivot table in a separate tab that shows mobile views represent 70.59% of all views in Wikipedia

The helper function receives the names of the columns to update and a function to call that can return the values for the columns.

After all of the columns are populated, we get a final Google sheet that includes an updated Pivot Table with a break down of the topic.

Python Building Blocks

Let’s learn some common Python building blocks while we review how Mueller’s code retrieves values to populate a couple of fields: the PageId and Description.

# Get the Wikipedia page ID -- needed for a bunch of items. Uses "Article" column def get_PageId(title): # Get page description from Wikipedia def get_description(pageId):

We have two Python functions to retrieve the fields. Python functions are like functions in Google Sheets but you define their behavior in any way you want. They take input, process it and return an output.

Here is the PageId we get when we call get_PageId(“Avengers: Endgame”)

'44254295'

Here is the Description we get when we call get_description(pageId)

'2024 superhero film produced by Marvel Studios'

Let’s step through, line by line, the get_PageId function to learn how it gets the ID of the title of the article that we are passing on.

# call the Wikipedia API to get the PageId of the article with the given title. q = {"action": "query", "format": "json", "prop": "info", "titles": title}

q is a Python dictionary. It holds key-value pairs. If you look up the value of “action”, you get “query” and so on. For example, you’d perform such a lookup using q[“action”].

“action” is a Python string. It represents textual information.

“titles”: title maps the “titles” key to the Python variable title that we passed as input to the function. All keys and values are hardcoded and explicit, except for the last one. This is what the dictionary looks like after we execute this function.

q = {"action": "query", "format": "json", "prop": "info", "titles": "Avengers: Endgame"}

In the next line we have.

Here we have a Python module function urllib.parse.urlencode. Module functions are just like Google sheet functions that provide standard functionality.

Before we call module or library functions, we need to import the module that contains them.

This line at the top of the notebook does that.

import urllib.parse

Let’s clarify the call and see the output we get.

urllib.parse.urlencode({"action": "query", "format": "json", "prop": "info", "titles": "Avengers: Endgame"})

You can find detailed documentation on the urlencode module function here. Its job is to convert a dictionary of URL parameters into a query string. A query string is the part of the URL after the question mark.

This is the output we get after we run it.

"action=query&format=json&prop=info&titles=Avengers%3A+Endgame"

This is what our URL definition line looks like after we add the result of urlencode.

The + sign here concatenates the strings to form one.

This resulting string is the API request the notebook sends to Wikipedia.

In the next line of code, we open the dynamically generated URL.

response = requests.get(url)

requests.get is a Python third-party module function. You need to install third-party libraries using the Python tool pip.

!pip install --upgrade -q requests

You can run command line script and tools from a notebook by prepending them with !

The code after ! is not Python code. It is Unix shell code. This article provides a comprehensive list of the most common shell commands.

After you install the third-party module, you need to import it like you do with standard libraries.

import requests

Here is what the translated call looks like.

You can open this request in the browser and see the API response from Wikipedia. The function call allows us to do this without manually opening a web browser.

The results from the chúng tôi call gets stored in the Python variable response.

This is what the result looks like.

{“batchcomplete”: “”,

“query”: {“pages”: {“44254295”: {“contentmodel”: “wikitext”,

“lastrevid”: 933501003,

“length”: 177114,

“ns”: 0,

“pageid”: 44254295,

“pagelanguage”: “en”,

“pagelanguagedir”: “ltr”,

“pagelanguagehtmlcode”: “en”,

“title”: “Avengers: Endgame”,

“touched”: “2024-01-03T17:13:02Z”}}}}

You can think of this complex data structure as a dictionary where some values include other dictionaries and so forth.

The next line of code slices and dices this data structure to extract the PageId.

result = list(response.json()["query"]["pages"].keys())[0]

Let’s step through it to see how it gets it.

response.json()["query"]

When we look up the value for the key “query”, we get a smaller dictionary.

{“pages”: {“44254295”: {“contentmodel”: “wikitext”,

“lastrevid”: 933501003,

“length”: 177114,

“ns”: 0,

“pageid”: 44254295,

“pagelanguage”: “en”,

“pagelanguagedir”: “ltr”,

“pagelanguagehtmlcode”: “en”,

“title”: “Avengers: Endgame”,

“touched”: “2024-01-03T17:13:02Z”}}}

Then, we look up the value of “pages” in this smaller dictionary.

response.json()["query"]["pages"]

We get an even smaller one. We are drilling down on the big response data structure.

{“44254295”: {“contentmodel”: “wikitext”,

“lastrevid”: 933501003,

“length”: 177114,

“ns”: 0,

“pageid”: 44254295,

“pagelanguage”: “en”,

“pagelanguagedir”: “ltr”,

“pagelanguagehtmlcode”: “en”,

“title”: “Avengers: Endgame”,

“touched”: “2024-01-03T17:13:02Z”}}

The PageId is available in two places in this slice of the data structure. As the only key, or as a value in the nested dictionary.

John made the most sensible choice, which is to use the key to avoid further exploration.

response.json()["query"]["pages"].keys()

The response from this call is a Python dictionary view of the keys. You can learn more about dictionary view in this article.

dict_keys(["44254295"])

We have what we are looking for, but not in the right format.

In the next step, we convert the dictionary view into a Python list.

list(response.json()["query"]["pages"].keys())

This what the conversion looks like.

["44254295"]

Python lists are like rows in a Google sheet. They generally contain multiple values separated by commas, but in this case, there is only one.

Finally, we extract the only element that we care about from the list. The first one.

list(response.json()["query"]["pages"].keys())[0]

The first element in Python lists starts at index 0.

Here is the final result.

"44254295"

As this is an identifier, is better to keep as a string, but if we needed a number to perform arithmetic operations, we would do another transformation.

int(list(response.json()["query"]["pages"].keys())[0])

In this case, we get a Python integer.

44254295

The main differences between strings and integers are the types of operations that you can perform with them. As you saw before we can use the + operator to concatenate two strings, but if we used the same operator in two numbers, it would add them together.

"44254295" + "3" = "442542953" 44254295 + 3 = 44254298

As a side note, I should mention jq, a cool command line tool that allows you to slice and dice JSON responses directly from curl calls (another awesome command line tool). curl allows you to do the equivalent of what we are doing with the requests module here, but with limitations.

So far we’ve learned how to create functions and data types that allow us to extract data and filter data from third-party sites (Wikipedia in our case).

Let’s call the next function in John’s notebook to learn another important building block: flow control structures.

get_description("442542953")

This is what the API URL looks like. You can try it in the browser.

Here what the response looks like.

{“ns”: 0,

“pageid”: 44254295,

“terms”: {“alias”: [“Avengers Endgame”, “Avengers End Game”, “Avengers 4”],

“description”: [“2024 superhero film produced by Marvel Studios”],

“label”: [“Avengers: Endgame”]},

“title”: “Avengers: Endgame”}

This is the code that will step through to understand control flows in Python.

# some pages don't have descriptions, so we can't blindly grab the value if "terms" in rs and "description" in rs["terms"]: result = rs["terms"]["description"][0] else: result = "" return result

This part checks if the response structure (above) includes a key named “terms”. It uses the Python If … Else control flow operator. Control flow operators are the algorithmic building blocks of programs in most languages, including Python.

if "terms" in rs

If this check is successful, we look up the value of such key with rs[“terms”]

We expect the result to be another dictionary and check it to see if there is a key with the value “description”.

"description" in rs["terms"]

If both checks are successful, then we extract and store the description value.

result = rs["terms"]["description"][0]

We expect the final value to be a Python list, and we only want the first element as we did before.

The and Python logical operator combines both checks into one where both need to be true for it to be true.

If the check is false, the description is an empty string.

result = "" Populating Google Sheets from Python

With a solid understanding of Python basic building blocks, now we can focus on the most exciting part of Mueller’s notebook: automatically populating Google Sheets with the values we are pulling from Wikipedia.

# by ‘functionToCall(parameterName)’. Show a progressbar while doing so. # Only calculate / update rows without values there, unless forceUpdate=True.

Let’s step through some interesting parts of this function.

The functionality to update Google Sheets is covered by a third-party module.

We need to install it and import it before we can use it.

!pip install --upgrade -q gspread import gspread

At the end of every helper function that fills a column, we have a call like the one above.

We are passing the relevant columns and the function that will get the corresponding values.

columnNr = df.columns.get_loc(fieldName) + 1 # column number of output field

The first thing we want to know is which column we need to update. When we run the code above we get 7, which is the column position of the PageId in the sheet (starting with 1).

for index, row in df.iterrows():

In this line of code, we have another control flow operator, the Python For Loops. For loops allow you to iterate over elements that represent collections, for example, lists and dictionaries.

In our case above, we are iterating over a dictionary where the index variable will hold the key, and the row variable will hold the value.

To be more precise, we are iterating over a Python dictionary view, a dictionary view is like a read-only and faster copy of the dictionary, which is perfect for iteration.

When you print iterrows, you don’t actually get the values, but a Python iterator object.

Iterators are functions that access data on demand, require less memory and perform faster than accessing collections manually.

INDEX: 2 ROW: Article César Alonso de las Heras Views 1,944,569 PartMobile 79.06% ViewsMobile 1,537,376 ViewsDesktop 407,193 PageId 18247033 Description WikiInLinks WikiOutLinks ExtOutLinks WikidataId WikidataInstance Name: 2, dtype: object sdsdsds

This is an example iteration of the for loop. I printed the index and row values.

# if we already did it, don't recalculate unless 'forceUpdate' is set. if forceUpdate or not row[fieldName]: result = functionToCall(row[parameterName])

forceUpdate is a Python boolean value which defaults to False. Booleans can only be true or false.

row[“PageId”] is empty initially, so not row[“PageId”] is true and the next line will execute. The or operator allows the next line to execute for subsequent runs only when the flag forceUpdate is true.

result = functionToCall(get_PageId)

This is the code that calls our custom function to get the page ids.

The result value for the example iteration is 39728003

When you review the function carefully, you will notice that we use df which is not defined in the function. The code that does that is at the beginning of the notebook.

# Convert to a DataFrame and render. # (A DataFrame is overkill, but I wanted to play with them more :)) import pandas as pd df = pd.DataFrame.from_records(worksheetRows)

The code uses the third-party module pandas to create a data frame from the Google Sheet rows. I recommend reading this 10 minutes to pandas article to get familiar. It is a very powerful data manipulation library.

Finally, let’s see how to we update the Google Sheet.

row[fieldName] = result # save locally worksheet.update_cell(index+1, columnNr, result) # update sheet too

This code can be translated to.

row["PageId"] = 39728003 # save locally worksheet.update_cell(3+1, 7, 39728003) # update sheet too

# (This is always confusing, but it works) from google.colab import auth auth.authenticate_user() import gspread from oauth2client.client import GoogleCredentials gc = gspread.authorize(GoogleCredentials.get_application_default()) worksheetRows = worksheet.get_all_values()

I left this code for last because it is the last thing that gets executed and it is also more complicated than the previous code. However, it is the first thing you need to execute in the notebook.

First, we import the third-party module gspread, and complete an Oauth authentication in Chrome to get access to Google Sheets.

worksheet = gc.open(“Wikipedia-Views-2024”).sheet1 worksheetRows = worksheet.get_all_values()

We manipulate the Google sheet with the worksheet variable and we use the worksheetRows variable to create the pandas Dataframe.

Visualizing from Python

Now we get to your homework.

I wrote code to partially reproduce John’s pivot table and plot a simple bar chart.

Your job is to add this code to your copy of the notebook and add print(varible_name) statements to understand what I am doing. This is how I analyzed John’s code.

Here is the code.

#Visualize from Python df.groupby("WikidataInstance").agg({"ViewsMobile": chúng tôi "ViewsDesktop": np.sum}) # the aggregation doesn't work because the numbers include commas # This gives an error ValueError: Unable to parse string "1,038,950,248" at position 0 #pd.to_numeric(df["ViewsMobile"]) # StackOverflow is your friend :) import locale from locale import atoi locale.setlocale(locale.LC_NUMERIC, '') #df[["ViewsMobile", "ViewsDesktop"]].applymap(atoi) df["ViewsMobile"] = df["ViewsMobile"].apply(atoi) df["ViewsDesktop"] = df["ViewsDesktop"].apply(atoi) # We try again and it works totals_df = df.groupby("WikidataInstance").agg({"ViewsMobile": chúng tôi "ViewsDesktop": np.sum}) totals_df #Here we plot totals_df.head(20).plot(kind="bar")

Resources to Learn More

How To Get The Last Element Of A List In Python?

In this article, we will show you how to get the last element of the input list using python. Now we see 4 methods to accomplish this task −

Using negative indexing

Using slicing

Using pop() method

Using For loop

Assume we have taken a list containing some elements. We will return the last element of the given input list using different methods as specified above.

Method 1: Using negative indexing

Python allows for “indexing from the end,” i.e., negative indexing.

This means that the last value in a sequence has an index of −1, the second last has an index of −2, and so on.

When you want to pick values from the end (right side) of an iterable, you can utilize negative indexing to your benefit

Syntax list[len − 1]: By definition, points to the last element. list[−1]: Negative indexing starting from the end Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

Create a variable to store the input list

Get the last element of the list using the “length of list – 1” as an index and print the resultant last element of the list.

Get the last element of the list using − 1(negative indexing) as the index and print the resultant last element of the list.

Example

The following program returns the last element of the input list using negative indexing −

inputList

=

[

5

,

1

,

6

,

8

,

3

]

print

(

“Input list:”

,

inputList

)

print

(

“Last element of the input list using len(list)-1 as index = “

,

inputList

[

len

(

inputList

)

1

]

)

print

(

“Last element of the input list using -1 as index = “

,

inputList

[

1

]

)

Output

On executing, the above program will generate the following output −

Input list: [5, 1, 6, 8, 3] Last element of the input list using len(list)-1 as index = 3 Last element of the input list using -1 as index = 3 Method 2: Using slicing

List slicing is a frequent practice in Python, and it is the most commonly utilized way for programmers to solve efficient problems. Consider a Python list. To access a range of elements in a list, you must slice it. One method is to utilize the simple slicing operator, i.e. colon (:)

With this operator, one can define where to begin slicing, where to end slicing and the step. List slicing creates a new list from an old one.

Syntax List[ start : end : step] Parameters

start– index from where to start

end – ending index

step – numbers of jumps to take in between i.e stepsize

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

Get the last element of the input list using slicing and create a variable to store it.

inputList[-1:][0] represents getting the first element by slicing it from the end of the list

Print the last element of the input list.

Example

The following program returns the last element of the input list using slicing −

inputList

=

[

5

,

1

,

6

,

8

,

3

]

print

(

“Input list:”

,

inputList

)

lastElement

=

inputList

[

1

:

]

[

0

]

print

(

“Last element of the input list = “

,

lastElement

)

Output Input list: [5, 1, 6, 8, 3] Last element of the input list = 3 Method 3: Using pop() method Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

Give the input list

Using the pop() function(removes the last element from a list and returns it), for getting the last element of the list

print the resultant last element of the list.

Example

The following program returns the last element of the input list using the pop() function −

inputList

=

[

5

,

1

,

6

,

8

,

3

]

print

(

“Input list:”

,

inputList

)

print

(

“Last element of the input list = “

,

inputList

.

pop

(

)

)

Output Input list: [5, 1, 6, 8, 3] Last element of the input list = 3 Method 4: Using For loop Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

Use the for loop, to traverse till the length of the list using the len() function(The number of items in an object is returned by the len() method)

Use the if conditional statement, to check whether the iterator value is equal to the length of the list -1.

Print the corresponding element of the list, if the condition is true.

Example

The following program returns the last element of the input list using the for loop −

inputList

=

[

5

,

1

,

6

,

8

,

3

]

print

(

“Input list:”

,

inputList

)

for

k

in

range

(

0

,

len

(

inputList

)

)

:

if

k

==

(

len

(

inputList

)

1

)

:

print

(

“Last element of the input list = “

,

inputList

[

k

]

)

Output Input list: [5, 1, 6, 8, 3] Last element of the input list = 3 Conclusion

We learned how to get the last element of a list using four different methods in this article: negative indexing, pop() function, negative indexing, and looping. We also learned how to use the pop() function to remove the last element from a list.

Update the detailed information about Python Program To Search An Element In An Array on the Cattuongwedding.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!