How do sort this list using one line? a_list.sort()



Similar documents
Programming Exercises

CS177 MIDTERM 2 PRACTICE EXAM SOLUTION. Name: Student ID:

Beginning to Program Python

Computer Science for San Francisco Youth

J a v a Quiz (Unit 3, Test 0 Practice)

Building Java Programs

Webair CDN Secure URLs

CSCE 110 Programming I Basics of Python: Variables, Expressions, and Input/Output

Python for Rookies. Example Examination Paper

Chapter 3 Writing Simple Programs. What Is Programming? Internet. Witin the web server we set lots and lots of requests which we need to respond to

Sorting. Lists have a sort method Strings are sorted alphabetically, except... Uppercase is sorted before lowercase (yes, strange)

Compsci 101: Test 1. October 2, 2013

NLP Lab Session Week 3 Bigram Frequencies and Mutual Information Scores in NLTK September 16, 2015

Computer Science 217

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Exercise 4 Learning Python language fundamentals

grep, awk and sed three VERY useful command-line utilities Matt Probert, Uni of York grep = global regular expression print

Python Lists and Loops

F ahrenheit = 9 Celsius + 32

Numeral Systems. The number twenty-five can be represented in many ways: Decimal system (base 10): 25 Roman numerals:

Python 3 Programming. OCR GCSE Computing

Sample CSE8A midterm Multiple Choice (circle one)

Introduction to: Computers & Programming: Review for Midterm 2

Python. KS3 Programming Workbook. Name. ICT Teacher Form. Do you speak Parseltongue?

Algorithm Design and Recursion

>

Outline Basic concepts of Python language

Introduction to Python for Text Analysis

Lab 5: HTTP Web Proxy Server

ESCI 386 IDL Programming for Advanced Earth Science Applications Lesson 6 Program Control

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

Program to solve first and second degree equations

Term Project: Roulette

Introduction to Java

Changing the Display Frequency During Scanning Within an ImageControls 3 Application

PIC 10A. Lecture 7: Graphics II and intro to the if statement

transmission media and network topologies client/server architecture layers, protocols, and sockets

Member Functions of the istream Class

if and if-else: Part 1

Iteration CHAPTER 6. Topic Summary

Introduction to Computer Science I Spring 2014 Mid-term exam Solutions

South East of Process Main Building / 1F. North East of Process Main Building / 1F. At 14:05 April 16, Sample not collected

CSIS 202: Introduction to Computer Science Spring term Midterm Exam

Systems Programming & Scripting

Python Objects. Charles Severance

Introduction to. Marty Stepp University of Washington

PYTHON Basics

Chapter 11. Talk To Your Computer

from Recursion to Iteration

Software Testing. Theory and Practicalities

HTSQL is a comprehensive navigational query language for relational databases.

Simulation Tools. Python for MATLAB Users I. Claus Führer. Automn Claus Führer Simulation Tools Automn / 65

Building Java Programs

CS170 Lab 11 Abstract Data Types & Objects

ESCI 386 Scientific Programming, Analysis and Visualization with Python. Lesson 5 Program Control

Project 2: Web Security Pitfalls

Chapter 2 Writing Simple Programs

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Automating SQL Injection Exploits

The Prime Numbers. Definition. A prime number is a positive integer with exactly two positive divisors.

Database trends: XML data storage

High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser)

AP Computer Science A 2011 Free-Response Questions

Outline. multiple choice quiz bottom-up design. the modules main program: quiz.py namespaces in Python

Sample Questions Csci 1112 A. Bellaachia

Introduction to Python

Computational Mathematics with Python

CSC 180 H1F Algorithm Runtime Analysis Lecture Notes Fall 2015

PHP Magic Tricks: Type Juggling. PHP Magic Tricks: Type Juggling

Pseudo code Tutorial and Exercises Teacher s Version

Visual Logic Instructions and Assignments

Introduction to Matlab

Feb 7 Homework Solutions Math 151, Winter Chapter 4 Problems (pages )

EE 261 Introduction to Logic Circuits. Module #2 Number Systems

Loop Invariants and Binary Search

Topic 11 Scanner object, conditional execution

Part I. Multiple Choice Questions (2 points each):

Computational Mathematics with Python

Introduction to Python

Lecture 2, Introduction to Python. Python Programming Language

CSC 221: Computer Programming I. Fall 2011

Solution for Homework 2

Analysis of Binary Search algorithm and Selection Sort algorithm

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

12-6 Write a recursive definition of a valid Java identifier (see chapter 2).

The While Loop. Objectives. Textbook. WHILE Loops

JavaScript and Dreamweaver Examples

Building Java Programs

Adafruit's Raspberry Pi Lesson 9. Controlling a DC Motor

Chapter 6: Episode discovery process

- Easy to insert & delete in O(1) time - Don t need to estimate total memory needed. - Hard to search in less than O(n) time

for while ' while ' for * for <var> in <sequence>: <body> $ %%" 0 *0

Transcription:

Review Questions for lists and File (read and write): Make sure to review Midterm 1 and midterm 2, all samples for midterms as well. Review all of the homework, class examples and readings exercises. Make sure to do the readings as well and review all of the class notes. 1) Given: >>> a_list = ["a", "b", "c", "d", "e", "f"] >>> a_list[1:3] ['b', 'c'] >>> a_list[:4] ['a', 'b', 'c', 'd'] >>> a_list[3:] ['d', 'e', 'f'] >>> a_list[:] ['a', 'b', 'c', 'd', 'e', 'f'] >>> a_list[- 1] [ 'f'] >>> a_list[::- 1] ['f', 'e', 'd','c', 'b', a'] How do sort this list using one line? a_list.sort()

How do you reverse the list using one line? a_list.reverse() How do you add the value 7 to the end of the list? a_list.append(7) How do you find in element a exists in list? If a in a_list: How do you count how many times the value c exists? print(a list.count( f )) How do you remove the value d from list? a_list.remove( d ) How do you find the length of the list? Len(a_list)

Write the following programs: 1) Call a function to initialize a list randomly (values should be between 1 and 100 inclusive and these values should be divisible evenly by 3 and 5. Then print the list. import random def rand(list): for i in range(1,101,1): # only select random numbers divisible evenly by 3 & 5 if (i%3 ==0 and i%5 ==0): list.append(random.randint(1,10)) print("list in rand function: ", list) def total(list): ''' function to print and compute total of elements in a list ''' tot=0 for item in list: tot += item print("total is: ", tot) num =[] print("list in main: ", num) rand(num)# you are now passing the address in memory where list is stored print("list in main: ", num) total(num)# compute total for all list values/elements

2) Read a list of words from file, and then search to see if that list includes the word Python. Count how many times Python appears in the file. If the word python appeared in the file, then write python and the number of times the word python appeared into a file? def searchfile(oldfile, newfile): f1 = open(oldfile, "r") f2 = open(newfile, "w") count=0 while True: text = f1.readline() if text == "": break if ("python" in text or "Python" in text): count += 1 f2.write(text) # if you find python then write it to file if count > 0: # print the count of Python in file f2.write("the number of times python appeared in file is : " + str( count) + "\n") f1.close() f2.close() oldfile = "languages.txt" newfile = 'python.txt' searchfile(oldfile, newfile)

3) [Sale application] Write a program that will call a function to decrease all of the list elements values (prices) by 40% when the items are on sale. Then call another function to increase all of the list elements values (prices) by 40% when the sale is over. prices = [100,20,50] print ("Prices from main before function call: ", prices) bf(prices) print ("Prices from main after function bf call: ", prices) orig(prices) print ("Prices from main before function orig call: ", prices) def bf(prices): for i in range (len(prices)): prices[i]= prices[i] *.6 def orig(prices): for i in range (len(prices)): prices[i]= prices[i]/.6

4) Ask the user to enter integers 1 to 12 for the month. Then, print the month such as January if the user entered 1 and December if the user entered 12. import random monthnumber = input('enter the month using a number from 1-12: ') mnumber= int(monthnumber) months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'Oct','November', 'December'] print('you picked: '+ printmonth(months,mnumber)) # Select a month at random from months list randommonth = pickrandommonth(months) print("month picked at random is: ", randommonth) def printmonth(months, mnumber): if mnumber < 1 or mnumber > 12: month = 'Error ' else: month = months[mnumber - 1] return month def pickrandommonth(months): rnum = random.randint(1, (len(months)- 1)) ranmonth = months[rnum] return ranmonth

5) Select a word from a list randomly and then ask the user to guess it in three trials. Make sure to give hints on the 2 nd and third trials such as the length of the string and the first character of the word. ''' read files a list of words and then assign all of the words to a list and then choose one word at random from the list. Then play a guess the secret word game in three trials. ''' import random names=[] #Global list # function to read words from file and assign it to a list def readfile(myfile): # read file myfile = open(myfile, "r") for line in myfile: name=line.rstrip('\n') names.append(name) def game(word): #play guess the secret word in 3 trials trial =1 secret="" secret= word.lower() keepgoing= True while(keepgoing): guess = input("try to guess the secret word: ") if ((guess.lower()) == secret): print("congratulations! You won in: ", trial, " trials") keepgoing = False break else:

if trial == 3: print("sorry! You lost the game. You used all your three chances", ". The secret word is: ", word) keepgoing = False break else: print("you have ", (3- trial), " trials remaining!") trial += 1 # function to select one word at random from list def selectrandom(): word = random.choice(names) print("word is :", word) return word # printing words.txt (names) print() #call function to read from file words.txt readfile('words.txt') #call function to select a word at random from list word = selectrandom() game(word)