2

Java – How To Read file and save data to ArrayList

we have to save ArrayList of names to a text file called “names.txt” in the previous article, Now in this article, we will read that file and save that saved data/items to ArrayList again

Code

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

public class Main {

    /**
     *
     * @param file_name
     * @param list
     */
    public static void read(String file_name, ArrayList<String> list) {
        try {
            File myObj = new File(file_name);
            try (Scanner myReader = new Scanner(myObj)) {
                while (myReader.hasNextLine()) {
                    String data = myReader.nextLine();
                    list.add(data);
                }
            }
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred.");
        }
    }

    public static void main(String[] args)
            throws FileNotFoundException, IOException, ClassNotFoundException {
        ArrayList<String> names = new ArrayList<>();
        read("names.txt", names);
        System.out.println(names);

    }

}

READ ALSO: Java – How To Write / Save ArrayList to a file

1

Java – How To Write / Save ArrayList to a file

Suppose we have ArrayList of some type of data and we want to save that ArrayList to file and need that data for later use. Today I will tell you how to save ArrayList to file, so let get started and save the ArrayList to a text file.

we have ArrayList named names of type String and we are goint to save all items in ArrayList to file,so below is the code of saving ArrayList data/items to a text file

Code

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;

public class Main {

    public static void save(String file_name,
            ArrayList<String> names) throws FileNotFoundException {
        PrintWriter pw = new PrintWriter(new FileOutputStream(file_name));
        for (String name : names) {
            pw.println(name);
        }
        pw.close();
    }

    public static void main(String[] args) throws FileNotFoundException {
        ArrayList<String> names = new ArrayList<>();
        names.add("John");
        names.add("Sam");
        names.add("Smith");
        names.add("Harry");
        save("names.txt", names);
        System.out.println("Array List save to file names.txt");

    }

}

After running the above code all names are saved in file “names.txt”, and we can read that file in the next part

READ ALSO: Java – How To Read file and save data to ArrayList

0

working with dictionaries and functions in python

Task

Create a program that initiates a sequence list of dictionaries as below:

NameAgeLength
Tom1980
John2090
Jony1791
Mick1588
Donal1689
David2185

This program has three functions in process module and these modules are:

  • sorting_by_name, this will return a sorted list dictionary based on the name
  • sorting_by_length, this will return a sorted list dictionary based on the length

sorting_by_age, this will return a sorted list dictionary based on the age

Code

from datetime import date

today = date.today().strftime("%b %d, %Y")
stu_data = [{"Name": "Tom","Age":19,"Length":80},
{"Name": "John","Age":20,"Length":90},
{"Name": "Jony","Age":17,"Length":91},
{"Name": "Mick","Age":15,"Length":88},
{"Name": "Donal","Age":16,"Length":89},
{"Name": "David","Age":21,"Length":85}
]

def sorting_by_name(list):
return sorted(list, key = lambda i: i['Name'])

def sorting_by_length(list):
return sorted(list, key = lambda i: i['Length'])

def sorting_by_age(list):
return sorted(list, key = lambda i: i['Age'])


print("Original Dictionary: ",stu_data)
print("Sorted_by_name: ",sorting_by_name(stu_data))
print("Sorted_by_length: ",sorting_by_length(stu_data))
print("Sorted_by_age: ",sorting_by_age(stu_data))

Output

Original Dictionary:  [{'Name': 'Tom', 'Age': 19, 'Length': 80},
{'Name': 'John', 'Age': 20, 'Length': 90},
{'Name': 'Jony', 'Age': 17, 'Length': 91},
{'Name': 'Mick', 'Age': 15, 'Length': 88},
{'Name': 'Donal', 'Age': 16, 'Length': 89},
{'Name': 'David', 'Age': 21, 'Length': 85}]
Sorted_by_name: [{'Name': 'David', 'Age': 21, 'Length': 85},
{'Name': 'Donal', 'Age': 16, 'Length': 89},
{'Name': 'John', 'Age': 20, 'Length': 90},
{'Name': 'Jony', 'Age': 17, 'Length': 91},
{'Name': 'Mick', 'Age': 15, 'Length': 88},
{'Name': 'Tom', 'Age': 19, 'Length': 80}]
Sorted_by_length: [{'Name': 'Tom', 'Age': 19, 'Length': 80},
{'Name': 'David', 'Age': 21, 'Length': 85},
{'Name': 'Mick', 'Age': 15, 'Length': 88},
{'Name': 'Donal', 'Age': 16, 'Length': 89},
{'Name': 'John', 'Age': 20, 'Length': 90},
{'Name': 'Jony', 'Age': 17, 'Length': 91}]
Sorted_by_age: [{'Name': 'Mick', 'Age': 15, 'Length': 88},
{'Name': 'Donal', 'Age': 16, 'Length': 89},
{'Name': 'Jony', 'Age': 17, 'Length': 91},
{'Name': 'Tom', 'Age': 19, 'Length': 80},
{'Name': 'John', 'Age': 20, 'Length': 90},
{'Name': 'David', 'Age': 21, 'Length': 85}]

keep visiting : shaadcoding

0

working with functions/methods in python

Task

Create two functions (generate_data and process_data) in python, where:

  • generate_data function will generate a sequence list from a random integer number based on the following specifications:
    • The function inputs are Length of list, start and end random number.
  • process_data function will process the input list data into this function to produce new output based on the following specifications:
    • The function inputs are data_list as a sequence list, operation_type as a string.
    • There will be three operation’s type:
      • “Sorting”, this will return an ascending sorted list
      • “Max”, this will return the maximum value in the input list
      • “Min”, this will return the minimum value in the input list

Code

from random import randrange
from datetime import date

today = date.today().strftime("%b %d, %Y")


def generate_data(n,start,end):
    list = []
    for i in range(n):
        num = randrange(start,end)
        list.append(num)
    return list

def process_data(data_list,operation_type):
    if operation_type.lower() == "sorting":
        data_list.sort()
        return data_list
    elif operation_type.lower() == "max":
        return max(data_list)
    elif operation_type.lower() == "min":
        return min(data_list.min())
    else:
        return data_list


n = int(input("length of list: "))
start = int(input("Start generating list: "))
end = int(input("End of generating list: "))
type_operation = input("Type of operation: ")

gen_list = generate_data(n,start,end)
print("The generated list is: ",gen_list)
proc_list = process_data(gen_list,type_operation)
print("The processed list is: ",proc_list)

Output

length of list: 10
Start generating list: 5
End of generating list: 25
Type of operation: max
The generated list is: [20, 7, 14, 10, 10, 13, 21, 24, 17, 5]
The processed list is: 24
n = int(input("length of list: "))

keep visiting : shaadcoding

1

working with lists, dictionaries, and tuples in python simultaneously

Task

Create a program that generates a list called keys and a list called values. Both lists should have same size n and generate from a random number between 0 to 30. Also, you need to

  • Convert the keys list to tuple tup_keys.
  • Convert the tup_keys and values into dictionary dic_list.
  • Update the value of the dictionary if the value is less than 5 add 10, and decrement by 6 if greater than 19.

Print the following values:

  • Two lists keys and values
  • New Tuple tup_keys
  • New dictionary dict_list
  • Sorted dict_list based on the Keys.
  • The max values in dict_keys
  • The output of the dict_list after updated the values.

Specifications

  • The program inputs are:
    • n is length of the list, ….                          (Must be integer and greater than 20)

Code

from random import randrange
n = 30
keys = []
values = []
#creating keys and values list with size equal to n
for i in range(n):
    num1 = randrange(0,30)
    num2 = randrange(0,30)
    keys.append(num1)
    values.append(num2)
#printing both lists
print("Keys List : ",keys)
print("Values List : ",values)

#converting list to tuples
tup_keys = tuple(keys)
dic_list = {}
#generating dictionary from tuple and value list
for i in range(n):
    dic_list[tup_keys[i]] = values[i]

#printing results
print("Tuple Keys : ",tup_keys)
print("New Dict list : ",dic_list)
print("Sorted dict list(based on keys) :",dict(sorted(dic_list.items(), key=lambda x: x[0])))
print("Max Value from dict key : ",max(dic_list.values()))
#updating values according to conditions given
for k,v in dic_list.items():
    if v < 5:
        v += 10
    elif v > 19:
        v -= 6
    dic_list[k] = v

#printing updated dictionary
print("Updated dict list : ",dic_list)

Output

Keys List :  [20, 6, 22, 4, 4, 28, 17, 23, 29,
              6, 22, 12, 16, 22, 7, 5, 5, 17,
              20, 21, 11, 23, 4, 5, 12, 8, 23,
              23, 24, 27]
Values List :  [9, 24, 3, 22, 23, 16, 6, 0, 14,
                13, 29, 21, 17, 7, 14, 14, 19,
                29, 8, 27, 0, 9, 1, 25, 19, 8,
                1, 4, 0, 21]
Tuple Keys :  (20, 6, 22, 4, 4, 28, 17, 23, 29,
               6, 22, 12, 16, 22, 7, 5, 5, 17, 
               20, 21, 11, 23, 4, 5, 12, 8, 23,
               23, 24, 27)
New Dict list :  {20: 8, 6: 13, 22: 7, 4: 1, 28: 16,
                  17: 29, 23: 4, 29: 14, 12: 19, 16: 17,
                  7: 14, 5: 25, 21: 27, 11: 0, 8: 8,
                  24: 0, 27: 21}
Sorted dict list(based on keys) : {4: 1, 5: 25, 6: 13,
                                   7: 14, 8: 8, 11: 0, 
                                   12: 19, 16: 17, 17: 29,
                                   20: 8, 21: 27, 22: 7,
                                   23: 4, 24: 0, 27: 21,
                                   28: 16, 29: 14}
Max Value from dict key :  29
Updated dict list :  {20: 8, 6: 13, 22: 7,
                      4: 11, 28: 16, 17: 23,
                      23: 14, 29: 14, 12: 19,
                      16: 17, 7: 14, 5: 19,
                      21: 21, 11: 10, 8: 8,
                      24: 10, 27: 15}

keep visiting : shaadcoding

0

printing sorted list, minimum and maximum value from the list, duplicate numbers from a list, and even numbers from the list in python

Task

Create a program to generate a list called num_list that has n elements from a random integer number between the start to end, and the output of this program should print the following:

  • The original generate list (num_list).
  • The sorted num_list.
  • The minimum and maximum value in num_list.
  • The list of duplication number from the num_list.
  • The only even numbers without duplication from the num_list.

Specifications

  • The program inputs are:
    • n is length of the list, ….                          (Must be integer and greater than 40)
    • start of random generation number.
    • end of random generation number.          (Must be integer and end greater than start)

Note:

  • You need to show the output result for all exception error output. For example, input the n is -90 or n is 30.
  • You can use this command to generate random number

Code

from random import randrange
n = int(input("Enter N : "))
num_list = []
even = set()

#checks if n is greater than 40
if n > 40:
    #taking start and end from user
    start = int(input("Enter Starting Number : "))
    end = int(input("Enter Ending Number : "))
    #checks if end is less than start
    if start < end:
        #generating num_list with size equal to n with random values between start and end
        for i in range(n):
            num = randrange(start,end)
            num_list.append(num)
            #if number generated is even then adding it to even set
            if num%2 == 0:
                even.add(num)

        #converting set to list
        even = list(even)
        seen = set()
        #finding duplicates items
        for x in num_list:
            if num_list.count(x) > 1:
                seen.add(x)
        dup = list(seen)
        #printing results
        print("Original List       : ",num_list)
        num_list.sort()
        print("Sorted List         : ",num_list)
        print("Max Value           : ",max(num_list))
        print("Min Value           : ",min(num_list))
        print("Duplication Numbers : ",dup)
        print("Even Numbers in List: ",even)

    else:
        print("Start must be less than End")
else:
    print("Value of n must be greater than 40")

Output

Enter N : 42
Enter Starting Number : 60
Enter Ending Number : 80
Original List : [72, 62, 61, 77, 66, 74,
66, 71, 66, 69, 76, 60,
77, 78, 61, 79, 61, 65,
60, 61, 77, 79, 74, 79,
64,63, 76, 69, 67, 66,
62, 78, 71, 69, 66, 76, 75,
63, 77, 61, 75]
Sorted List : [60, 60, 61, 61, 61, 61, 61,
62, 62, 63, 63, 64, 65, 66,
66, 66, 66, 66, 67, 69, 69,
69, 71, 71, 72, 74, 74, 75,
75, 76, 76, 76, 77, 77, 77,
77, 77, 78, 78, 79, 79, 79]
Max Value : 79
Min Value : 60
Duplication Numbers : [66, 69, 71, 74, 75, 76, 77,
78, 79, 60, 61, 62, 63]
Even Numbers in List: [64, 66, 72, 74, 76, 78, 60, 62]

keep visiting : shaadcoding

0

Processing multiple text files using python

Included in USAOnline is the baby name file for 1986 (yob1986.txt). For this
assignment, you will need to read in both the 1986 and 2016 (yob2016.txt) files. The user
should enter a baby name to search for. Your program should not only give the total (not separated
by gender) number of babies named that for both 1986 and 2016, but also give the percentage
change from 1986 to 2016 for that name

Code

f = open("yob2016.txt")
f2 = open("yob1986.txt")
names_data_2016 = {}
names_data_1986 = {}
for row in f:
row = row.rstrip()
data = row.split(",")
name = data[0]
count = int(data[2])
if name not in names_data_2016.keys():
names_data_2016[name] = 0
names_data_2016[name] += count

for row in f2:
row = row.rstrip()
data = row.split(",")
name = data[0]
count = int(data[2])
if name not in names_data_1986.keys():
names_data_1986[name] = 0
names_data_1986[name] += count

name = input("Enter name : ").title()
if name in names_data_2016 and name in names_data_1986:
count_2016 = names_data_2016[name]
count_1986 = names_data_1986[name]
print(name,"in 2016 counts =",count_2016)
print(name,"in 1986 counts =",count_1986)
total = count_2016 + count_1986
change = count_2016 - count_1986
st = "increases"
if change < 0:
st = "decreases"
change = change * -1
percentage = round((change * 100) / total,2)
print(f"Percentage change from 1986 to 2016 {st} by {percentage}%")
else:
print("Name not in files")

Output

keep visiting : shaadcoding

1

processing text files using python

Working with the 2016 baby name file (yob2016.txt) again, your code should
calculate the total number of babies whose names begin with each letter of the alphabet. Then,
your code should print out a nicely formatted table with each letter of the alphabet and the total
number of babies with names beginning with that letter.

Code

f = open("yob2016.txt")
letters_count = {}
for row in f:
    row = row.rstrip()
    data = row.split(",")
    name = data[0]
    count = data[2]
    if name[0] not in letters_count.keys():
        letters_count[name[0]] = 0
    letters_count[name[0]] += int(count)
print('{:<15} | {:<15} '.format("LETTER","COUNT"))
print("="*30)
for k in sorted(letters_count):
    print('   {:<10}   | {:<15} '.format(k,letters_count[k]))
print("="*30)

Output

keep visiting : shaadcoding

0

python bill calculator for grocery shop project using file handling and lists

Assume that the user has a file (named grocerylist.dat) which includes a
grocery list with three columns of data: the name of the item, the quantity of the item to be bought,
and the price of each item. These columns are separated by commas. There is also a header line for
the file.
Your program should read in this file, print out a well-formatted table with each item, as well as its
quantity, price, and total price.

Code

f = open("grocerylist.dat")
header = f.readline().split(",")

print('{:<20} | {:<15} | {:<20} | {:<20}'.format(header[0],header[1],header[2].rstrip() ,'TOTAL'))
print("="*70)
i = 0
final_total = 0
for row in f:
row = row.rstrip()
data = row.split(",")
item = data[0]
qnty = data[1]
price = data[2]
total = float(qnty) * float(price)
final_total += total
print('{:<20} | {:<15} | {:<20} | {:<20.2f}'.format(item,qnty,price ,total))
print("="*70)
print('{:<20} {:<15} {:<20} | {:<20.2f}'.format("FINAL TOTAL","","" ,final_total))

Output

output

keep visiting : shaadcoding

2

Rock, Paper, Scissors, Saw Game in Python

Project requires students to create a design for a text-based “Rock, Paper, Scissors, and Saw”
game and then implement it in Python.

Scope

The software to be created will be a stand-alone PC representation of the hand game called
“Rock, Paper, Scissors, and Saw”, implemented with procedural approach using Python. It will
have two human players and a computer acting as the third player.

General Description

When user(s) starts the program, he will be prompted for the names of the two human players.
These values will be used for all prompts and statistics in the program.
Then there will be a menu with the following selections: “1. Play game”, “2. Show game rules”,
“3. Show statistics”, and “4. Exit” in that order. Rules selection will provide rules of the game,
statistics will show the accumulative wins, loses, and ties per each player (both rounds and
games), and exit will close the program.
When play game is selected, each player will be able to select his weapon (rock, paper, scissors,
or saw) and computer will make its choice. Each of the players will be playing against the
computer. A game will consist of 3 rounds. After each round either a player or computer will be
the winner of the round and after 3 rounds, again either computer or player will be the winner of
the game. User(s) will be able to run multiple games and their wins/loses/ties will be displayed in
the statistics option along with the overall human winner.

CODE

import random

games = [[0,0],[0,0],[0,0],[0,0]]
rounds = [[0,0],[0,0],[0,0],[0,0]]

def check_name(name):
if not name:
return False
elif len(name) < 5 or len(name) > 20:
return False
else:
return True
def player1_name():
while True:
name = input("What is the name of the first player?")
if check_name(name):
return name
else:
print("Name must contain letters(5-20)")
def player2_name(p1):
while True:
name = input("What is the name of the second player?")
if check_name(name):
if name.lower() == p1.lower():
print("Second player name must be different from first player")
else:
return name
else:
print("Name must contain letters(5-20)")
def menu():
while True:
print("1. Play game")
print("2. Show game rules")
print("3. Show statistics")
print("4. Exit")
ch = input("Enter your choice : ")
if ch.isdigit() and int(ch) > 0 and int(ch) <= 4:
return int(ch)
else:
print("choice must be from 1 - 5")
def rules():
print('''[R4.1] When game starts, each Player gets prompted for his selection of Rock, Paper, Scissors,
and Saw. The prompt must use the player’s name.
[R4.2] Computer makes its random selection to be used against each player (same selection
will be used against both human players)
Software Requirements Specification Page iii
<RPS Game>
[R4.3] For each player, program displays that player’s selection, computer’s selection and who
won that round (computer or player)
[R4.4] Next round repeats the prompting and announcement of the round winners. This is
repeated for a total of 3 rounds.
[R4.5] Once all 3 rounds are completed winners of the game are announced for each player.
Just like rounds, each player is playing against the computer and so the winner of the game is
either the player or the computer.
[R4.6] The winner of the game is one who won most rounds. The program must account for
ties. For example, if a player won 2 rounds and lost 1 round, then he won the game against the
computer. If the player won 1 round, lost 1 round, and tied 1 round then he tied the game
against the computer.
[R4.7] After game winners are announced, user is able to go back to menu where they can
again select one of the options.
[R4.8] Users can play as many games as they want''')
def valid_weapon(w):
if w not in ['rk', 'pr', 'sc', 'sw']:
return False
return True

def check_winner(w1,w2):
if w1 == w2:
return -1
if w1=='rk':
if w2 in ['sc','sw']:
return 1
return 2
if w1 == 'sc':
if w2 in ['rk','sw']:
return 2
else:
return 1
if w1 == 'pr':
if w2 in ['sc','sw']:
return 2
else:
return 1
if w1 == 'sw':
if w2 in ['sc','pr']:
return 1
else:
return 2
def play(p1,p2):
round = 0
gwinner1 = 0
gwinner2 = 0
while round != 3:
print(f"ROUND {round+1}\n***************")
print("Enter 'rk' for Rock, 'pr' for Paper, 'sc' for Scissors, 'sw' for Saw")
w1 = input(f"{p1}'s weapon? : ")
if valid_weapon(w1):
while True:
w2 = input(f"{p2}'s weapon? : ")
if valid_weapon(w2):
break
else:
print("invalid choice!!!")
continue
cw = random.choice(['rk', 'pr', 'sc', 'sw'])
#print(cw)
winner1 = check_winner(w1,cw)
rounds[0][0] += 1
rounds[0][1] += 1
if winner1 == -1:
rounds[3][0] += 1
print(f"{p1} ties in round {round + 1} against computer")
elif winner1 == 1:
rounds[1][0] += 1
gwinner1 += 1
print(f"{p1} wins in round {round+1} against computer")
else:
rounds[2][0] += 1
print(f"{p1} lose in round {round + 1} against computer")
winner2 = check_winner(w2,cw)
if winner2 == -1:
rounds[3][1] += 1
print(f"{p2} ties in round {round + 1} against computer")
elif winner2 == 1:
rounds[1][1] += 1
gwinner2 += 1
print(f"{p2} wins in round {round + 1} against computer")
else:
rounds[2][1] += 1
print(f"{p2} lose in round {round + 1} against computer")
round += 1


else:
print("invalid choice!!!")
continue
games[0][0] += 1
games[0][1] += 1
print("\n******Game Result*****")
if gwinner1 == gwinner2:
games[3][0] += 1
games[3][1] += 1
print("Game ties")
if gwinner1 < gwinner2:
games[1][1] += 1
games[2][0] += 1
print(f"{p2} wins")
if gwinner1 > gwinner2:
games[1][0] += 1
games[2][1] += 1
print(f"{p1} wins")
input("Enter to continue...")


def stats(p1,p2):
print("\n******STATS******\n")
print(f"{p1} STATS")
print(f"Total Games = ",games[0][0])
print(f"Games Won = ",games[1][0])
print(f"Games Lost = ",games[2][0])
print(f"Games Ties = ",games[3][0])
print(f"Total Rounds = ",rounds[0][0])
print(f"Rounds Won = ",rounds[1][0])
print(f"Rounds Lost = ",rounds[2][0])
print(f"Rounds Ties = ",rounds[3][0])
print()
print(f"{p2} STATS")
print(f"Total Games = ", games[0][1])
print(f"Games Won = ", games[1][1])
print(f"Games Lost = ", games[2][1])
print(f"Games Ties = ", games[3][1])
print(f"Total Rounds = ", rounds[0][1])
print(f"Rounds Won = ", rounds[1][1])
print(f"Rounds Lost = ", rounds[2][1])
print(f"Rounds Ties = ", rounds[3][1])

def main():
p1 = player1_name()
p2 = player2_name(p1)
while True:
ch = menu()
if ch == 1:
play(p1,p2)
elif ch == 2:
rules()
elif ch == 3:
stats(p1,p2)
elif ch == 4:
print("Good Bye!")
break

if __name__ == '__main__':
main()

Demo

keep visiting : shaadcoding