Python programming problems and

Содержание
  1. Intermediate Coding Problems in Python
  2. Infinite Monkey Theorem
  3. Practice Python Exercises and Challenges with Solutions
  4. Basic Exercise for Beginners
  5. Python Input and Output Exercise
  6. Python Loop Exercise
  7. Python Functions Exercise
  8. Python String Exercise
  9. Python Data Structure Exercise
  10. Python List Exercise
  11. Python Dictionary Exercise
  12. Python Set Exercise
  13. Python Tuple Exercise
  14. Python Date and Time Exercise
  15. Python OOP Exercise
  16. Python JSON Exercise
  17. Python NumPy Exercise
  18. Python Pandas Exercise
  19. Python Matplotlib Exercise
  20. Random Data Generation Exercise
  21. Python Database Exercise
  22. Exercises for Intermediate developers
  23. Exercise 1: Reverse each word of a string
  24. Exercise 2: Read text file into a variable and replace all newlines with space
  25. Exercise 3: Remove items from a list while iterating
  26. Exercise 4: Reverse Dictionary mapping
  27. Exercise 5: Display all duplicate items from a list
  28. Exercise 6: Filter dictionary to contain keys present in the given list
  29. Exercise 7: Print the following number pattern
  30. Exercise 8: Create an inner function
  31. Exercise 9: Modify the element of a nested list inside the following list
  32. Exercise 10: Access the nested key increment from the following dictionary
  33. Python Object-Oriented Programming (OOP) Exercise: Classes and Objects Exercises
  34. Python Date and Time Exercise with Solutions
  35. Python Dictionary Exercise with Solutions
  36. Python Tuple Exercise with Solutions
  37. Python Set Exercise with Solutions
  38. Python if else, for loop, and range() Exercises with Solutions
  39. Python Functions Exercise
  40. Python Input and Output Exercise
  41. Python List Exercise with Solutions
  42. Python JSON Exercise
  43. Python Data Structure Exercise for Beginners
  44. Python String Exercise with Solutions
  45. Python Matplotlib Exercise
  46. Python Pandas Exercise
  47. Python NumPy Exercise
  48. Python Basic Exercise for Beginners
  49. Useful Python Tips and Tricks Every Programmer Should Know
  50. Python random Data generation Exercise
  51. Python Database Programming Exercise
  52. Online Python Code Editor
  53. About PYnative
  54. Explore Python
  55. Follow Us
  56. Legal Stuff
Читайте также:  Php create table insert into

Intermediate Coding Problems in Python

Python, being a very dynamic and versatile programming language, is used in almost every field. From software development to machine learning, it covers them all. This article will focus on some interesting coding problems which can be used to sharpen our skills a bit more and at the same time, have fun solving this list of specially curated problems. Although this article will focus on solving these problems using Python, one can feel free to use any other language of their choice. So let’s head right into it!

Infinite Monkey Theorem

The theorem states that a monkey hitting keys at random on a typewriter keyboard for an infinite amount of time will almost surely type a given text, such as the complete works of William Shakespeare. Well, suppose we replace a monkey with a Python function. How long would it take for a Python function to generate just one sentence? The sentence we will go for is: “a computer science portal for geeks”.
The way we will simulate this is to write a function that generates a string that is 35 characters long by choosing random letters from the 26 letters in the alphabet plus space. We will write another function that will score each generated string by comparing the randomly generated string to the goal. A third function will repeatedly call generate and score, then if 100% of the letters are correct we are done. If the letters are not correct then we will generate a whole new string. To make it easier to follow, our program should keep track of the best string generated so far.

Читайте также:  Node js или питон

Источник

Practice Python Exercises and Challenges with Solutions

Free Coding Exercises for Python Developers. Exercises cover Python Basics, Data structure, to Data analytics. As of now, this page contains 18 Exercises.

What included in these Python Exercises?

Each exercise contains specific Python topic questions you need to practice and solve. These free exercises are nothing but Python assignments for the practice where you need to solve different programs and challenges.

  • All exercises are tested on Python 3.
  • Each exercise has 10-20 Questions.
  • The solution is provided for every question.
  • Practice each Exercise in Online Code Editor

These Python programming exercises are suitable for all Python developers. If you are a beginner, you will have a better understanding of Python after solving these exercises. Below is the list of exercises.

Select the exercise you want to solve.

Basic Exercise for Beginners

Practice and Quickly learn Python’s necessary skills by solving simple questions and problems.

Topics: Variables, Operators, Loops, String, Numbers, List

Python Input and Output Exercise

Solve input and output operations in Python. Also, we practice file handling.

Topics: print() and input() , File I/O

Python Loop Exercise

This Python loop exercise aims to help developers to practice branching and Looping techniques in Python.

Topics: If-else statements, loop, and while loop.

Python Functions Exercise

Practice how to create a function, nested functions, and use the function arguments effectively in Python by solving different questions.

Topics: Functions arguments, built-in functions.

Python String Exercise

Solve Python String exercise to learn and practice String operations and manipulations.

Python Data Structure Exercise

Practice widely used Python types such as List, Set, Dictionary, and Tuple operations in Python

Python List Exercise

This Python list exercise aims to help Python developers to learn and practice list operations.

Python Dictionary Exercise

This Python dictionary exercise aims to help Python developers to learn and practice dictionary operations.

Python Set Exercise

This exercise aims to help Python developers to learn and practice set operations.

Python Tuple Exercise

This exercise aims to help Python developers to learn and practice tuple operations.

Python Date and Time Exercise

This exercise aims to help Python developers to learn and practice DateTime and timestamp questions and problems.

Topics: Date, time, DateTime, Calendar.

Python OOP Exercise

This Python Object-oriented programming (OOP) exercise aims to help Python developers to learn and practice OOP concepts.

Topics: Object, Classes, Inheritance

Python JSON Exercise

Practice and Learn JSON creation, manipulation, Encoding, Decoding, and parsing using Python

Python NumPy Exercise

Practice NumPy questions such as Array manipulations, numeric ranges, Slicing, indexing, Searching, Sorting, and splitting, and more.

Python Pandas Exercise

Practice Data Analysis using Python Pandas. Practice Data-frame, Data selection, group-by, Series, sorting, searching, and statistics.

Python Matplotlib Exercise

Practice Data visualization using Python Matplotlib. Line plot, Style properties, multi-line plot, scatter plot, bar chart, histogram, Pie chart, Subplot, stack plot.

Random Data Generation Exercise

Practice and Learn the various techniques to generate random data in Python.

Topics: random module, secrets module, UUID module

Python Database Exercise

Practice Python database programming skills by solving the questions step by step.

Use any of the MySQL, PostgreSQL, SQLite to solve the exercise

Exercises for Intermediate developers

The following practice questions are for intermediate Python developers.

If you have not solved the above exercises, please complete them to understand and practice each topic in detail. After that, you can solve the below questions quickly.

Exercise 1: Reverse each word of a string

Expected Output

  • Use the split() method to split a string into a list of words.
  • Reverse each word from a list
  • finally, use the join() function to convert a list into a string

Steps to solve this question:

  • Split the given string into a list of words using the split() method
  • Use a list comprehension to create a new list by reversing each word from a list.
  • Use the join() function to convert the new list into a string
  • Display the resultant string
# Exercise to reverse each word of a string def reverse_words(Sentence): # Split string on whitespace words = Sentence.split(" ") # iterate list and reverse each word using ::-1 new_word_list = [word[::-1] for word in words] # Joining the new list of words res_str = " ".join(new_word_list) return res_str # Given String str1 = "My Name is Jessa" print(reverse_words(str1)) 

Exercise 2: Read text file into a variable and replace all newlines with space

Given: Assume you have a following text file (sample.txt).

Line1 line2 line3 line4 line5

Expected Output:

Line1 line2 line3 line4 line5
  • First, read a text file.
  • Next, use string replace() function to replace all newlines ( \n ) with space ( ‘ ‘ ).

Steps to solve this question: —

  • First, open the file in a read mode
  • Next, read all content from a file using the read() function and assign it to a variable.
  • Next, use string replace() function to replace all newlines ( \n ) with space ( ‘ ‘ ).
  • Display final string
with open('sample.txt', 'r') as file: data = file.read().replace('\n', ' ') print(data)

Exercise 3: Remove items from a list while iterating

Description:

In this question, You need to remove items from a list while iterating but without creating a different copy of a list.

Remove numbers greater than 50

number_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

Expected Output: —

  • Get the list’s size
  • Iterate list using while loop
  • Check if the number is greater than 50
  • If yes, delete the item using a del keyword
  • Reduce the list size

Solution 1: Using while loop

number_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] i = 0 # get list's size n = len(number_list) # iterate list till i is smaller than n while i < n: # check if number is greater than 50 if number_list[i] >50: # delete current index from list del number_list[i] # reduce the list size n = n - 1 else: # move to next item i = i + 1 print(number_list)

Solution 2: Using for loop and range()

number_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] for i in range(len(number_list) - 1, -1, -1): if number_list[i] > 50: del number_list[i] print(number_list)

Exercise 4: Reverse Dictionary mapping

Expected Output:

ascii_dict = # Reverse mapping new_dict = print(new_dict)

Exercise 5: Display all duplicate items from a list

sample_list = [10, 20, 60, 30, 20, 40, 30, 60, 70, 80]

Expected Output: —

  1. Use the counter() method of the collection module.
  2. Create a dictionary that will maintain the count of each item of a list. Next, Fetch all keys whose value is greater than 2

Solution 1: — Using collections.Counter()

import collections sample_list = [10, 20, 60, 30, 20, 40, 30, 60, 70, 80] duplicates = [] for item, count in collections.Counter(sample_list).items(): if count > 1: duplicates.append(item) print(duplicates)
sample_list = [10, 20, 60, 30, 20, 40, 30, 60, 70, 80] exist = <> duplicates = [] for x in sample_list: if x not in exist: exist[x] = 1 else: duplicates.append(x) print(duplicates)

Exercise 6: Filter dictionary to contain keys present in the given list

# Dictionary d1 = # Filter dict using following keys l1 = ['A', 'C', 'F']

Expected Output: —

# Dictionary d1 = # Filter dict using following keys l1 = ['A', 'C', 'F'] new_dict = print(new_dict)

Exercise 7: Print the following number pattern

1 1 1 1 1 2 2 2 2 3 3 3 4 4 5

Refer to Print patterns in Python to solve this question.

  • set x = 0
  • Use two for loops
  • The outer loop is reverse for loop from 5 to 0
  • Increment value of x by 1 in each iteration of an outer loop
  • The inner loop will iterate from 0 to the value of i of the outer loop
  • Print value of x in each iteration of an inner loop
  • Print newline at the end of each outer loop
rows = 5 x = 0 # reverse for loop from 5 to 0 for i in range(rows, 0, -1): x += 1 for j in range(1, i + 1): print(x, end=' ') print('\r')

Exercise 8: Create an inner function

Question description: —

  • Create an outer function that will accept two strings, x and y . ( x= ‘Emma’ and y = ‘Kelly’ .
  • Create an inner function inside an outer function that will concatenate x and y.
  • At last, an outer function will join the word ‘developer’ to it.

Expected Output: —

def manipulate(x, y): # concatenate two strings def inner_fun(x, y): return x + y z = inner_fun(x, y) return z + 'Developers' result = manipulate('Emma', 'Kelly') print(result) 

Exercise 9: Modify the element of a nested list inside the following list

Change the element 35 to 3500

list1 = [5, [10, 15, [20, 25, [30, 35], 40], 45], 50]

Expected Output: —

[5, [10, 15, [20, 25, [30, 3500], 40], 45], 50]
list1 = [5, [10, 15, [20, 25, [30, 35], 40], 45], 50] # modify item list1[1][2][2][1] = 3500 # print final result print(list1) # print(list1[1]) = [10, 15, [20, 25, [30, 400], 40], 45] # print(list1[1][2]) = [20, 25, [30, 400], 40] # print(list1[1][2][2]) = [30, 40] # print(list1[1][2][2][1]) = 40

Exercise 10: Access the nested key increment from the following dictionary

emp_dict = < "company": < "employee": < "name": "Jess", "payable": < "salary": 9000, "increment": 12 >> > > print(emp_dict['company']['employee']['payable']['increment'])

Under Exercises: —

Python Object-Oriented Programming (OOP) Exercise: Classes and Objects Exercises

Updated on: December 8, 2021 | 47 Comments

Python Date and Time Exercise with Solutions

Updated on: December 8, 2021 | 9 Comments

Python Dictionary Exercise with Solutions

Python Tuple Exercise with Solutions

Updated on: December 8, 2021 | 83 Comments

Python Set Exercise with Solutions

Updated on: October 20, 2022 | 24 Comments

Python if else, for loop, and range() Exercises with Solutions

Updated on: September 6, 2021 | 257 Comments

Python Functions Exercise

Python Input and Output Exercise

Updated on: September 6, 2021 | 89 Comments

Python List Exercise with Solutions

Updated on: December 8, 2021 | 173 Comments

Python JSON Exercise

Updated on: December 8, 2021 | 6 Comments

Python Data Structure Exercise for Beginners

Updated on: December 8, 2021 | 107 Comments

Python String Exercise with Solutions

Updated on: October 6, 2021 | 195 Comments

Python Matplotlib Exercise

Python Pandas Exercise

Python NumPy Exercise

Python Basic Exercise for Beginners

Updated on: September 26, 2022 | 428 Comments

Useful Python Tips and Tricks Every Programmer Should Know

Python random Data generation Exercise

Updated on: December 8, 2021 | 13 Comments

Python Database Programming Exercise

Online Python Code Editor

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use, Cookie Policy, and Privacy Policy.

Copyright © 2018–2023 pynative.com

Источник

Оцените статью