CS50-Python实验3,4
Posted sinowind
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CS50-Python实验3,4相关的知识,希望对你有一定的参考价值。
Week3 Exceptions
Fuel Gauge
题目描述:
输入分数字符串,判断并输出相应的百分数;特例不足1%输出E,超出99%输出F
思路:
1,从字符串中取出x,y;
2,按题中要求计算输出;
题解:
while True:
try:
## 取出x,y
x, z, y= input("Fraction: ")
x, y = int(x), int (y)
##防止出错
if y == 0:
raise ZeroDivisionError
if x > y:
raise ValueError
break
except(ValueError, ZeroDivisionError):
pass
## 模拟题
if 0 < x/y < 0.99:
print(f"round(x/y*100)%")
elif x/y >= 0.99:
print("F")
else:
print("E")
Felipe’s Taqueria
题目描述:
根据用户输入的信息,匹配菜单价格,最终算出最终价格。
题解:
## 菜单信息
menu =
"Baja Taco": 4.00,
"Burrito": 7.50,
"Bowl": 8.50,
"Nachos": 11.00,
"Quesadilla": 8.50,
"Super Burrito": 8.50,
"Super Quesadilla": 9.50,
"Taco": 3.00,
"Tortilla Salad": 8.00,
##total:结果
total = 0
## 计算输出
while True:
try:
## title(): 首字母大写其余小写
item = input("Item: ").title()
if item in menu:
total += menu[item]
print(f"Total: $total:.2f")
except EOFError:
print()
break
Grocery List
题目描述:
记录用户输入商品,最终输出已输入的商品以及商品数量;
题解:
## 存储商品信息
list =
while True:
## 输入处理
try:
## upper():字符串大写
item = input("").upper()
except EOFError:
print()
break
## 记录商品
if item in list:
list[item] += 1
else:
list[item] = 1
## 输出结果
for item, cnt in sorted(list.items()):
print(f"cnt item")
Outdated
题目描述:
用户输入9/8/1636,September 8, 1636形式,系统转换输出1636-09-08;若用户输出其他形式抛异常。
题解:
## 月份记录
months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
]
##思路:分情况讨论
while True:
date = input("Date: ")
month,day,year = "", "", ""
try:
## 9/8/1636
if len(date.split("/")) == 3:
date = date.split("/")
month, day, year = map(int, date)
## September 8, 1636
else:
date = date.split(",")
if len(date) == 2:
month, day = date[0].split()
month = months.index(month)+1
day, year = int(day), int(date[1])
##输出
if 1<=int(month)<=12 and 1<=int(day)<=31:
print(f"year:04-month:02-day:02")
break
except ValueError:
pass
Week4 Libraries
Emojize
题目描述:
练习python调用库操作;
题解:
from emoji import emojize
print("Output:", emojize(input("Input: ")))
Frank, Ian and Glen’s Letters
题目描述:
The documentation for pyfiglet isn’t very clear, but you can use the module as follows:
from pyfiglet import Figlet
figlet = Figlet()
You can then get a list
of available fonts with code like this:
figlet.getFonts()
You can set the font with code like this, wherein f
is the font’s name as a str
:
figlet.setFont(font=f)
And you can output text in that font with code like this, wherein s
is that text as a str
:
print(figlet.renderText(s))
题解:
from pyfiglet import Figlet
import random
import sys
fonts = Figlet().getFonts()
# Zero if the user would like to output text in a random font.
# Two if the user would like to output text in a specific font, in which case the first of the two should be -f or --font, and the second of the two should be the name of the font.
if len(sys.argv) == 1:
font = random.choice(fonts)
elif len(sys.argv) == 3:
if sys.argv[1] in ["-f", "--font"] and sys.argv[2] in fonts:
font = sys.argv[2]
else:
sys.exit("Invalid arguments.")
else:
sys.exit("Invalid number of arguments.")
## 输出
text = input("Input: ")
print("Output:\\n", Figlet(font=font).renderText(text))
Adieu, Adieu
题目描述:
用户输入名字,将所有名字按照inflect中的操作输出;
题解:
import inflect
p = inflect.engine()
names = []
while True:
try:
names.append(input("Name: ").strip())
except EOFError:
print()
break
print(f"Adieu, adieu, to p.join(names)")
Guessing Game
题目描述:
用户选择猜数等级,然后进行竞猜。竞猜过程中会提示用户信息,直到猜中为止;
题解:
from random import randint
## 选择猜数等级
while True:
try:
n = int(input("Level: "))
if n < 0:
raise ValueError
break
except ValueError:
pass
## 生成竞猜的数
rand = randint(1, n)
## 用户判断
while True:
try:
guess = int(input("Guess: "))
if guess < rand:
print("Too small!")
elif guess > rand:
print("Too large!")
else:
print("Just right!")
break
except ValueError:
pass
Little Professor
题目描述:
用户选择等级进行随机式子生成,最后根据算式正确结果算取所得分数;
题解:
import random
def main():
level = get_level()
score = 0
for _ in range(10):
x = generate_integer(level)
y = generate_integer(level)
## 计算score
tries = 0
while tries < 3:
try:
tries += 1
answer = int(input(f"x + y = "))
if answer == x+y:
score += 1
break
else:
print("EEE")
except ValueError:
pass
print(f"x + y = x+y")
print("Score", score)
## 获取等级
def get_level():
while True:
try:
level = int(input("Level: "))
if level in [1, 2, 3]:
return level
except ValueError:
pass
## 在范围内生成数字
def generate_integer(level):
if level == 1:
return random.randint(0, 9)
return random.randint(10 ** (level - 1), 10**level - 1)
if __name__ == "__main__":
main()
Bitcoin Price Index
题目描述:
Expects the user to specify as a command-line argument the number of Bitcoins n, that they would like to buy. If that argument cannot be converted to a float
, the program should exit via sys.exit
with an error message.
Queries the API for the CoinDesk Bitcoin Price Index at https://api.coindesk.com/v1/bpi/currentprice.json, which returns a JSON object, among whose nested keys is the current price of Bitcoin as a float
. Be sure to catch any exceptions, as with code like:
import requests
try:
...
except requests.RequestException:
...
Outputs the current cost of Bitcoins in USD to four decimal places, using ,
as a thousands separator.
题解:
import sys
import requests
try:
response = requests.get("https://api.coindesk.com/v1/bpi/currentprice.json")
data = response.json()
current_price = data["bpi"]["USD"]["rate_float"]
except requests.RequestException:
sys.exit()
try:
n = float(sys.argv[1])
except IndexError:
sys.exit("Missing command-line argument")
except ValueError:
sys.exit("Command-line argument is not a number")
print(f"$n * current_price:,.4f")
大数据Hadoop实验报告
文章目录
实验一 熟悉常用的Linux操作和Hadoop操作
1.实验目的
Hadoop运行在Linux系统上,因此,需要学习实践一些常用的Linux命令。本实验旨在熟悉常用的Linux操作和Hadoop操作,为顺利开展后续其他实验奠定基础。
2.实验平台
- 操作系统:Linux;
- Hadoop版本:2.7.1。
3.实验内容和要求
(一)熟悉常用的Linux操作
请按要求上机实践如下linux基本命令。
cd命令:切换目录
(1)切换到目录 /usr/local
(2)切换到当前目录的上一级目录
(3)切换到当前登录Linux系统的用户的自己的主文件夹
ls命令:查看文件与目录
(4)查看目录/usr下所有的文件
mkdir命令:新建新目录
(5)进入“/tmp”目录,创建一个名为“a”的目录,并查看“/tmp”目录下已经存在哪些目录
(6)进入“/tmp”目录,创建目录“a1/a2/a3/a4”
rmdir命令:删除空的目录
(7)将上面创建的目录a(在“/tmp”目录下面)删除
(8)删除上面创建的目录“a1/a2/a3/a4” (在“/tmp”目录下面),然后查看“/tmp”目录下面存在哪些目录
cp命令:复制文件或目录
(9)将当前用户的主文件夹下的文件.bashrc复制到目录“/usr”下,并重命名为bashrc1
(10)在目录“/tmp”下新建目录test,再把这个目录复制到“/usr”目录下
mv命令:移动文件与目录,或更名字
(11)将“/usr”目录下的文件bashrc1移动到“/usr/test”目录下
(12)将“/usr”目录下的test目录重命名为test2
rm命令:移除文件或目录
(13)将“/usr/test2”目录下的bashrc1文件删除
$ sudo rm /usr/test2/bashrc1
(14)将“/usr”目录下的test2目录删除
$ sudo rm –r /usr/test2
cat命令:查看文件内容
(15)查看当前用户主文件夹下的.bashrc文件内容
tac命令:反向查看文件内容
(16)反向查看当前用户主文件夹下的.bashrc文件的内容
more命令:一页一页翻动查看
(17)翻页查看当前用户主文件夹下的.bashrc文件的内容
head命令:取出前面几行
(18)查看当前用户主文件夹下.bashrc文件内容前20行
(19)查看当前用户主文件夹下.bashrc文件内容,后面50行不显示,只显示前面几行
tail命令:取出后面几行
(20)查看当前用户主文件夹下.bashrc文件内容最后20行
(21) 查看当前用户主文件夹下.bashrc文件内容,并且只列出50行以后的数据
touch命令:修改文件时间或创建新文件
(22)在“/tmp”目录下创建一个空文件hello,并查看文件时间
(23)修改hello文件,将文件时间整为5天前
chown命令:修改文件所有者权限
(24)将hello文件所有者改为root帐号,并查看属性
find命令:文件查找
(25)找出主文件夹下文件名为.bashrc的文件
tar命令:压缩命令
(26)在根目录“/”下新建文件夹test,然后在根目录“/”下打包成test.tar.gz
(27)把上面的test.tar.gz压缩包,解压缩到“/tmp”目录
$ sudo tar -zxv -f /test.tar.gz -C /tmp
grep命令:查找字符串
(28)从“~/.bashrc”文件中查找字符串’examples’
(29)请在“~/.bashrc”中设置,配置Java环境变量
(30)查看JAVA_HOME变量的值
(二)熟悉常用的Hadoop操作
(31)使用hadoop用户登录Linux系统,启动Hadoop(Hadoop的安装目录为“/usr/local/hadoop”),为hadoop用户在HDFS中创建用户目录“/user/hadoop”
(32)接着在HDFS的目录“/user/hadoop”下,创建test文件夹,并查看文件列表
(33)将Linux系统本地的“~/.bashrc”文件上传到HDFS的test文件夹中,并查看test
(34)将HDFS文件夹test复制到Linux系统本地文件系统的“/usr/local/hadoop”目录下
实验二 熟悉常用的HDFS操作
1.实验目的
- 理解HDFS在Hadoop体系结构中的角色;
- 熟练使用HDFS操作常用的Shell命令;
2.实验平台
- 操作系统:Linux(建议Ubuntu16.04);
- Hadoop版本:2.7.1;
- JDK版本:1.7或以上版本;
- Java IDE:Eclipse。
3.实验步骤
(一)编程实现以下功能,并利用Hadoop提供的Shell命令完成相同任务:
(1)向HDFS中上传任意文本文件,如果指定的文件在HDFS中已经存在,则由用户来指定是追加到原有文件末尾还是覆盖原有的文件;
Shell命令:
追加到末尾
hadoop fs -appendToFile /usr/local/hadoop/test.txt /user/text.txt
覆盖原文件
hadoop fs -copyFromLocal -f /usr/local/hadoop/test.txt /user/text.txt
Java代码:
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import java.io.*;
public class HDFSApi
public static boolean test(Configuration conf, String path) throws IOException FileSystem fs = FileSystem.get(conf);
return fs.exists(new Path(path));
public static void copyFromLocalFile(Configuration conf, String localFilePath, String remoteFilePath) throws IOException
FileSystem fs = FileSystem.get(conf);
Path localPath = new Path(localFilePath);
Path remotePath = new Path(remoteFilePath); fs.copyFromLocalFile(false, true, localPath, remotePath);
fs.close();
public static void appendToFile(Configuration conf, String localFilePath, String remoteFilePath) throws IOException
FileSystem fs = FileSystem.get(conf);
Path remotePath = new Path(remoteFilePath);
FileInputStream in = new FileInputStream(localFilePath);
FSDataOutputStream out = fs.append(remotePath);
byte[] data = new byte[1024];
int read = -1;
while ( (read = in.read(data)) > 0 ) out.write(data, 0, read);
out.close(); in.close(); fs.close();
public static void main(String[] args)
Configuration conf = new Configuration(); conf.set("fs.default.name","hdfs://localhost:9000");
String localFilePath = "/home/hadoop/text.txt";
String remoteFilePath = "/user/hadoop/text.txt";
String choice = "append";
String choice = "overwrite";
try
Boolean fileExists = false;
if (HDFSApi.test(conf, remoteFilePath))
fileExists = true;
System.out.println(remoteFilePath + " 已存在.");
else
System.out.println(remoteFilePath + " 不存在.");
if ( !fileExists) // 文件不存在,则上传
HDFSApi.copyFromLocalFile(conf, localFilePath, remoteFilePath);
System.out.println(localFilePath + " 已上传至 " + remoteFilePath);
else if ( choice.equals("overwrite") ) // 选择覆盖
HDFSApi.copyFromLocalFile(conf, localFilePath, remoteFilePath);
System.out.println(localFilePath + " 已覆盖 " + remoteFilePath);
else if ( choice.equals("append") ) // 选择追加
HDFSApi.appendToFile(conf, localFilePath, remoteFilePath);
System.out.println(localFilePath + " 已追加至 " + remoteFilePath);
catch (Exception e)
e.printStackTrace();
(2)从HDFS中下载指定文件,如果本地文件与要下载的文件名称相同,则自动对下载的文件重命名;
Shell命令:
if $(hadoop fs -test -e /usr/local/hadoop/test.txt);
then $(hadoop fs -copyToLocal /user/test.txt /usr/local/hadoop/test.txt);
else $(hadoop fs -copyToLocal /user/test.txt /usr/local/hadoop/test2.txt);
Java代码:
Import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import java.io.*;
public class HDFSApi
public static void copyToLocal(Configuration conf, String remoteFilePath, localFilePath) throws IOException
FileSystem fs = FileSystem.get(conf);
Path remotePath = new Path(remoteFilePath);
File f = new File(localFilePath);
if(f.exists())
System.out.println(localFilePath + " 已存在.");
Integer i = 0;
while (true)
f = new File(localFilePath + "_" + i.toString());
if (!f.exists())
localFilePath = localFilePath + "_" + i.toString();
break;
System.out.println("将重新命名为: " + localFilePath); ());
Path localPath = new Path(localFilePath);
fs.copyToLocalFile(remotePath, localPath);
fs.close();
public static void main(String[] args)
Configuration conf = new Configuration(); conf.set("fs.default.name","hdfs://localhost:9000");
String localFilePath = "/home/hadoop/text.txt";
String remoteFilePath = "/user/hadoop/text.txt";
try
HDFSApi.copyToLocal(conf, remoteFilePath, localFilePath);
System.out.println("下载完成");
catch (Exception e)
e.printStackTrace();
(3)将HDFS中指定文件的内容输出到终端中;
Shell命令:
hadoop fs -cat text.txt
Java代码:
import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.*; import java.io.*;
public class HDFSApi
/**
* 读取文件内容
*/
public static void cat(Configuration conf, String remoteFilePath) throws IOException
FileSystem fs = FileSystem.get(conf);
Path remotePath = new Path(remoteFilePath);
FSDataInputStream in = fs.open(remotePath);
BufferedReader d = new BufferedReader(new InputStreamReader(in)); String line = null;
while ( (line = d.readLine()) != null )
System.out.println(line);
d.close(); in.close(); fs.close();
public static void main(String[] args)
Configuration conf = new Configuration(); conf.set("fs.default.name","hdfs://localhost:9000");
String remoteFilePath = "/user/local/hadoop/text.txt"; // HDFS 路径
try
System.out.println("读取文件: " + remoteFilePath);
HDFSApi.cat(conf, remoteFilePath);
System.out.println("\\n 读取完成");
catch (Exception e)
e.printStackTrace();
(4)显示HDFS中指定的文件的读写权限、大小、创建时间、路径等信息;
Shell命令:
hadoop fs -ls -h /user/test.txt
Java代码:
import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.*; import java.io.*; import java.text.SimpleDateFormat;
public class HDFSApi
public static void ls(Configuration conf, String remoteFilePath) throws IOException
FileSystem fs = FileSystem.get(conf);
Path remotePath = new Path(remoteFilePath); FileStatus[] fileStatuses = fs.listStatus(remotePath); for (FileStatus s : fileStatuses)
System.out.println("路径: " + s.getPath().toString());
System.out.println("权限: " + s.getPermission().toString());
System.out.println("大小: " + s.getLen());
/* 返回的是时间戳,转化为时间日期格式 */
Long timeStamp = s.getModificationTime();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = format.format(timeStamp);
System.outprintln("时间: " + date); fs.close();
public static void main(String[] args) Configuration conf = new Configuration(); conf.set("fs.default.name","hdfs://localhost:9000");
String remoteFilePath = "/user/hadoop/text.txt";
try
System.out.println("读取文件信息: " + remoteFilePath);
HDFSApi.ls(conf, remoteFilePath);
System.out.println("\\n 读取完成");
catch (Exception e)
e.printStackTrace();
(5)给定HDFS中某一个目录,输出该目录下的所有文件的读写权限、大小、创建时间、路径等信息,如果该文件是目录,则递归输出该目录下所有文件相关信息;
Shell命令:
hadoop fs -ls -R -h /user
Java代码
import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.*; import java.io.*;
import java.text.SimpleDateFormat;
public class HDFSApi
/**
* 显示指定文件夹下所有文件的信息(递归)
*/
public static void lsDir(Configuration conf, String remoteDir) throws IOException
FileSystem fs = FileSystem.get(conf);
Path dirPath = new Path(remoteDir);
/* 递归获取目录下的所有文件 */
RemoteIterator<LocatedFileStatus> remoteIterator = fs.listFiles(dirPath, true);
/* 输出每个文件的信息 */
while (remoteIterator.hasNext())
FileStatus s = remoteIterator.next();
System.out.println("路径: " + s.getPath().toString());
System.out.println("权限: " + s.getPermission().toString());
System.out.println("大小: " + s.getLen());
/* 返回的是时间戳,转化为时间日期格式 */
Long timeStamp = s.getModificationTime();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = format.format(timeStamp);
System.out.println("时间: " + date);
System.out.println();
fs.close();
/**
* 主函数
*/
public static void main以上是关于CS50-Python实验3,4的主要内容,如果未能解决你的问题,请参考以下文章