python tutorial with exercises

Read about python tutorial with exercises, The latest news, videos, and discussion topics about python tutorial with exercises from alibabacloud.com

Python exercises 035:project Euler 007:10,001th Prime

Topic from Project Euler 7th: https://projecteuler.net/problem=7# Project Euler:problem 7:10001st prime# by listing the first six prime numbers:# 2, 3, 5, 7, one, and six, we can see tha T the 6th Prime is 13.# What's the 001st prime number?# answer:104743import timedef f (x): #判断 x is a prime number, returns a bool value if x = = 2: return True elif x Solve the 10,001th prime number.The idea of the above code is quite simple: first customize a function to determine whether a

Python exercises 037:project Euler 009: The product of the Pythagorean ternary group

Topic from Project Euler 9th: https://projecteuler.net/problem=9# Project Euler:problem 9:special Pythagorean triplet# A Pythagorean triplet is a set of three natural numbers,# a If the problem is clear, it is quite simple, but to find a combination of various a+b+c=1000, and then verify that a**2 + b**2 = c**2 on the line. Traversal range, because aWhat do you mean, "Pythagoras triples"? is not "tick the law" in the "hook three four strings five"? Indeed, the ancient Chinese people are not very

Python Grammar exercises-user management

Program Requirements:1. Determine if the user is blacklisted, matching blacklist exit program2. Determine the user name and password entered, three times to exit the program, and blacklist#!/usr/bin/env python#!-*-Coding:utf8-*-#Write user nameuser_name = open ("/tmp/name.txt","W") User_name.write ("Jin\ntom\njak\nsum") User_name.close ()#Write PasswordUSER_PASSWD = open ("/tmp/passwd.txt","W") User_passwd.write ("123456\N67890\NQWERT\NASDFG") User_pa

Python Grammar Exercises--string formatting

#!/usr/bin/env python#-*-Coding:utf8-*-w_sex = "female" m_sex = "male" w_age = 23m_age = 25sex_input = input ("Please enter your Gender:"). Strip () a ge_input = Int (input ("Please enter your Age:")) if sex_input = = W_sex and age_input >= w_age:print ("Your information is as follows: \ n Sex:%s\n Age:%s\n You belong to a late marriage year. Age "% (sex_input,age_input)) elif Sex_input = = M_sex and age_input >= m_age:print (" Your information is as

Chapter 2 of Python natural language processing exercises 12 and Chapter 2

Chapter 2 of Python natural language processing exercises 12 and Chapter 2 Problem description: CMU pronunciation dictionary contains multiple pronunciations of certain words. How many different words does it contain? What is the proportion of words with multiple pronunciations in this dictionary? Because nltk. corpus. cmudict. entries () cannot use the set () method to remove duplicate words. It can only

Python exercises----Find out which user has the highest ad cost

duplicated and needs to be aggregated by the user.Code implementation, there is nothing special, read 3 files, load the content into the Python data structure, and then sum, Sort, print.In order to highlight features, the code does not have validation code.#-*-coding:utf-8-*-fromcollectionsimportdefaultdictclick= The defaultdict (list) ads=defaultdict (list) users={}# stores 3 files in the 3 dictionaries above with Open ("click", "R") asf:foriinf: v=

Python-Statistical system memory exercises

Statistics system memory, and then see how much of the percentage is occupied.The method of the string: A.startswith () returns a bool (Boolean) value.A.split () Splits spaces and tabs, and then returns a list.#!/usr/bin/python#coding: UTF8With open ('/proc/meminfo ') as FD:For line in FD:If Line.startswith (' Memtotal '):Total = Int (Line.split () [1])ContinueIf Line.startswith (' Memfree '):free = Int (Line.split () [1])Print "%.2f"% (free/1024.0) +

Getting started with Python--data structure exercises

2015.9.7A=[11,22,24,29,30,32]1) Insert 28 into the end of List Aa=[11,22,24,29,30,32]a.append ()2) Insert 57 after 29A.insert (4,57)3) Sort a list elements from small to largeA.sort ()4) Change the first element of List A to 6A[0]=65) Delete Element 32A.pop (-1)Del A[-1]b=[1,2,3,4,5]1) Output The following results in 2 ways:[1,2,3,4,5,6,7,8]b=b+[6,7,8]B.extend ([6,7,8])2) Return the result using the 2 methods of the list: [5,4]Print B[-1:-3:-1]c=[]c.append (B.pop ()) C.append (B.pop ())3) Determ

Python exercises 2

]): month2=i lis.append (month2) day2=remindays-sum (month_days[:i]) lis.append (day2) break Print "%d days after the date is: %d%d months%d"% (num,lis[0],lis[1],lis[2]) Else: Print "%d days after the date is: %d%d months%d"% (num,year1,12,31) #elif sumdays==0: #print "date%d days is:%d%d months%d"% (num,year1,1,1) Else: Lis=[] remindays=0 years2=years1 year2=year1ifsumdays0:#if Year2%4==0: #years2=366 #e

Python core programming chapter sixth exercises

6-6 Creating a similar String.strip () functionMethod an inefficient method for copying and generating substring objects in large numbers def Str_strip (s):While Len (s) >=2:If s[0]== ':S=s[1:]ElseBreakWhile Len (s) >=2:If s[-1]== ':S=S[:-1]ElseBreakIf s== ' or s== ':Return 'Elsereturn s Method Two: Convert to List def Str_strip (s): if s = = "or S = =" ": Return "" #to List Elif Len (s) >=2: L = List (s) While L and l[0] = = "":

Python 17.6.20 Exercises

1 The contents of the document are as follows: Name, gender, age, salaryEgon Male 18 3000Alex Male 38 30000Wupeiqi Female 28 20000Yuanhao Female 28 10000Requirements:Remove each record from the file into the list,Each element of the list is {' name ': ' Egon ', ' sex ': ' Male ', ' age ': the form of ' salary ': 3000}2 based on the list obtained by 1, take out the information of the person with the highest salary3 based on 1 to the list, take out the information of the youngest person4 based on

"Python Natural Language Processing" chapter II Exercise solution exercises 6

translate[' tu '] does not display correctly you (singular), thou, but will error Keyerror: ' Tu ':1 >>> translate['tu']2Traceback (most recent Call last):3 "" in 4 'tu'Solution Ideas:Traversing the list of languages, when a many-to-many relationship is detected, the element is processed and then added to the original language list.Code:1 fromNltk.corpusImportSwadesh2 Swadesh.fileids ()3It2en = Swadesh.entries (['it','en'])4De2en = Swadesh.entries (['de','en'])5 6 forKeyinchIt2en:7 if

Python Basics Exercises Pat Water problem (iv)

#学习笔记#用以练习python基础#Original title Link: https://www.patest.cn/contests/pat-b-practise/10501050. Spiral Matrix (25)The subject requires that the given n positive integers be filled in the "Spiral Matrix" in a non-ascending order. The so-called "spiral Matrix" refers to the 1th grid in the upper left corner, which is filled in a clockwise spiral direction. The scale of the requirement matrix is m row n column, satisfies the condition: M*n equals n;m>=n;

Python Core Programming Second Edition second chapter exercises

2.12.32.42.52.62.72.82.92.102.11deftest_sum (): Tup=("1","2","3","6","5") Sum=0 forIinchTup:sum=float (i) +sumreturnsumdeftest11 (): whiletrue:string=raw_input (">>") ifstring=="1": Sum=test_sum ()Print "sum:", Sumelifstring=="2": Sum=test_sum () Avg=sum/5Print"avg:", Avgelifstring=="x": Exit ()Else: Print"Please enter 1 or 2 or x"test11 ()2.12-2.132.15B:deftest15 (): Num1=raw_input ("First num:") num2=raw_input ("Second num:") num3=raw_input ("Third num:") NUM1=float (NUM1) nu

Python exercises 1 Optimization: Saving user information to a file

]=newcontentPrint "modified successfully! "Content[index]=userdict Breakcontentdict=content fo=open (filename,"W") forIinchcontentdict:i=Str (i) Fo.write (i+'\ n') Fo.close ()defchoice ():Print"\ n" Print "make a choice: 1, add user, 2, user list, 3, search user, 4, modify user, 5, Exit!" Print"\ n"Choice=raw_input ("Please make a choice:") ifchoice=="1": Add_user ()elifChoice = ="2": List_user ()elifchoice=="3": Search_user ()elifchoice=="4": Modify_user ()elifchoice=="5":

Python algorithm Exercises

1. Insert Sort:Insert Sort By default the first is the list that is already sorted, after each one is compared and sorted, after the row, all the natural has been lined up, the second optimization algorithm, if it has been inserted, to find the right position, then break, if you do not need to sort, then it is already the largest, Because the front has been lined up, after the row, there is no need to row, you can break.Import Timestart = Lambda:time.time () List1 = [66,33,1,3,111,3,10,29,7,123,

Python Basics Exercises

1. Simple input/output interaction>>> name='hy'print('hi,%s. '%name ' Hi,hy. >>> name=input (' pleaseinput:') "pleaseinput:print (name)2, the user input two numbers, calculate and output two numbers of the sum:# user Input number number1=input (' Enter first number:') number2=input (' Enter first number:')# sum sum=float (number1) +float (number2)# Display The results of the calculation print(' two numbers add up to:', float (number1) +float ( NUMBER2))3. Enter the radius to calculate the are

Python Basics Exercises

1. Simple input/output interaction.Number=input (' Please enter a number:')print(numbers)2. The user enters two numbers, calculates and outputs the sum of two digits: (try to do this with just one line of code)# user input digital fir = input (' Enter first number:'= input (' Enter second number:') )# sum sum = float (FIR) + float (sec)# Show calculation results Print(' two numbers added result:', float (FIR) + float (sec))3. Enter a radius to calculate the area of the circle.q=3.14# user i

Python Basics Exercises

Simple input-output interaction.# input n=input (' Please enter:')# output print(n)Please enter: zzzz the user enters two numbers, calculates and outputs two numbers of the sum: (try to do this with one line of code) print ( " Two sum of%2f "% (float (input (" Please enter the number 1: )) +float ( " Please enter the number 2: " )) Please enter a number 1:5 Enter the number 2: 10 15.000000 Enter a radius to calculate the area of the circle.# Enter Radius r=input (' Please

"Python exercises" string fragment

Tag: Col Class log means question preserves AAA output styleA string of lowercase letters can be considered as the largest fragment of some same letter. For example, "AAABBAAAC" is made up of the following fragments: ' aaa ', ' BB ', ' C '. Bull Ox now given a string, please help calculate the average length of all fragments of this string.Input Description:The input includes a string s, the length of the string s (1≤length≤50), and S contains only lowercase letters (' a '-' Z ')Output Descripti

Total Pages: 15 1 .... 11 12 13 14 15 Go to: Go

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.