How to loop hashes within an array - arrays

I need to use a loop in my code so the user is prompted with "Name?" three times, and each answer is stored as a new hash within the data array. Each answer should also have a new random number generated for it, and an email.
I need puts data to output all three hashes and their contents. I've tried using 3.times do, but I'm having trouble:
data = Array.new()
puts "Name?, eg. Willow Rosenberg"
name = gets.chomp
number = rand(1000..9000) + 1
data = [
{
name: name,
number: number,
email: name.split(' ').last + number.to_s[1..3] + "#btvs.com"
}
]
puts data

data = []
3.times do
puts "Name?, eg. Willow Rosenberg"
name = gets.chomp
number = rand(1000..9000) + 1
hash = {
name: name,
number: number,
email: name.split(' ').last + number.to_s[1..3] + "#btvs.com"
}
data << hash
end
puts data

Related

Strings: How to combine first and last names in a long text string with other words?

Problem:
I have a given string = "Hello #User Name and hello again #Full Name and this works"
Desired output: = ["#User Name, #Full Name"]
Code I have in Swift:
let commentString = "Hello #User Name and hello again #Full Name and this works"
let words = commentString.components(separatedBy: " ")
let mentionQuery = "#"
for word in words.filter({ $0.hasPrefix(mentionQuery) }) {
print(word) = prints out each single name word "#User" and "#Full"
}
Trying this:
if words.filter({ $0.hasPrefix(mentionQuery) }).isNotEmpty {
print(words) ["Hello", "#User", "Name".. etc.]
}
I'm stuck on how to get an array of strings with the full name = ["#User Name", "#Full Name"]
Would you know how?
First of all, .filter means that check each value in the array which condition you given and if true then take value - which not fit here.
For the problem, it can divide into two task: Separate string into substring by " " ( which you have done); and combine 2 substring which starts with prefix "#"
Code will be like this
let commentString = "Hello #User Name and hello again #Full Name"
let words = commentString.components(separatedBy: " ")
let mentionQuery = "#"
var result : [String] = []
var i = 0
while i < words.count {
if words[i].hasPrefix(mentionQuery) {
result.append(words[i] + " " + words[i + 1])
i += 2
continue
}
i += 1
}
The result
print("result: ", result) // ["#User Name", "#Full Name"]
You can also use filter, like this below:
let str = "Hello #User Name and hello again #Full Name"
let res = str.components(separatedBy: " ").filter({$0.hasPrefix("#")})
print(res)
// ["#User", "#Full"]

How to find the index of a value in an array and use it to display a value in another array with the same index

I am new to Python and I have been stuck trying out a "simple banking program".
I have got everything right except for this bit:
If the user types S then:
Ask the user for the account number.
Search the array for that account number and find its position in the accountnumbers array.
Display the Name, and balance at the position found during the above search.
Originally it was just supposed to be through accounts 1-5, but now I am having trouble coming up with a way to search the account numbers if they are any number, not just 1 - 5. For example
The user makes his account numbers 34, 445, 340,2354 and 3245. Completely random account numbers with no order.
Here is what I have so far
names = []
accountNumbers = []
balance = []
def displaymenu():
print("**** MENU OPTIONS ****")
print("Type P to populate accounts")
print("Type S to search for account")
print("Type E to exit")
choiceInput()
def choiceInput():
choice = str(input("Please enter your choice: "))
if (choice == "P"):
populateAccount()
elif (choice == "S"):
accountNumb = int(input("Please enter the account number to search: "))
if (accountNumb > 0) and (accountNumb < 6):
print("Name is: " + str(names[accountNumb - 1]))
print(names[accountNumb - 1] + " account has the balance of : $" + str(balance[accountNumb -1]))
elif (accountNumb == accountNumbers):
index = names.index(accountNumb)
accountNumb = index
print(names[accountNumb - 1] + " account has the balance of : $" + str(balance[accountNumb -1]))
else:
print("The account number not found!")
elif (choice == "E"):
print("Thank you for using the program.")
print("Bye")
raise SystemExit
else:
print("Invalid choice. Please try again!")
displaymenu()
def populateAccount ():
name = 0
for name in range(5):
Names = str(input("Please enter a name: "))
names.append(Names)
account ()
name = name + 1
def account ():
accountNumber = int(input("Please enter an account number: "))
accountNumbers.append(accountNumbers)
balances()
def balances ():
balances = int(input("Please enter a balance: "))
balance.append(balances)
displaymenu()
I have tried to use indexes and have not been able to find a solution.
Replace the following line of code
if (accountNumb > 0) and (accountNumb < 6):
with
if (accountNumb > 0) and (accountNumb < len(accountNumbers)):
My mistake. I messed up when appending the account number:
def account ():
accountNumber = int(input("Please enter an account number: "))
accountNumbers.append(accountNumbers)
balances()
I appended
accountNumbers
not
accountNumber
the code should be
def account ():
accountNumber = int(input("Please enter an account number: "))
accountNumbers.append(accountNumber)
balances()
also the searchArray function I made was:
def searchArray(accountNumbers):
x = int(input("Please enter an account number to search: "))
y = accountNumbers.index(x)
print("Name is: " + str(names[y]))
print(str(names[y]) + " account has a balance of: " + str(balance[y]))
rookie mistake , shouldnt be using such similar object names.

python arraylist distribution

def createlist(json, filename, arraygroup):
filehdl = open(filename, "wb")
for key, value in rulegroup.items():
filehdl.write('#' + value + "\n")
for list in json:
if list['arraygroup'] == value:
filehdl.write(list['name'] + " " + list['surname'] + "\n")
filehdl.close()
#depart1
testname testsurname
testname1 testsurname2
testname3 testsurname3
#depart2
#depart3
Json has 5 names, and 2 names should be places in #depart2, #depart3 base on their correct department.
Hi i have here a code that will create a file and separate the names in json file base on there group, but the 2nd forloop (with json) was not resetting its index, so after 1st loop of the forloop list was stuck.
tnx for answer.^^,
I already resolve the problem by inputing json obj to array.
jsonlist = []
for obj in json:
jsonlist.append(obj)
then change the 2nd loop with jsonlist
for list in jsonlist:
if list['arraygroup'] == value:
filehdl.write(list['name'] + " " + list['surname'] + "\n")

Adding an Array to an Array Ruby

Im trying to learn how to add arrays into arrays, I have the following code:
puts "would you like to save a data set"
response = gets.chomp
if response == "y"
puts "create a new dataset?"
create_data_set = gets.chomp
while create_data_set == "y"
puts "what do you want to name the data set?"
dataset = gets.chomp
dataset = Array.new
puts 'would you like to add some grades to the array?'
store_grades_response = gets.chomp
while store_grades_response == "y"
puts 'enter grade ->'
grade = gets.chomp.to_i
dataset << grade
puts 'would you like to store another grade?'
store_grades_response = gets.chomp
end
all_data_sets = Array.new
all_data_sets.push(dataset)
puts "would you like to create a new data set?"
create_data_set = gets.chomp
end
end
puts all_data_sets
Im basically asking a user to enter a array name which should create an array, add values to the array and if required by the user add some more arrays and values to it. At last the array should be added to an array. And then I'm trying to display all the arrays.
The code works fine, I'm looping through everything but when it puts all_data_sets It only shows the last array that was created? i would like to store all the arrays within the one array called all_data_sets
The problem is that you are creating a new array all_data_sets at the end of each loop. One solution will be to have it before the loop.
puts "would you like to save a data set"
response = gets.chomp
all_data_sets = []
if response == "y"
puts "create a new dataset?"
create_data_set = gets.chomp
while create_data_set == "y"
puts "what do you want to name the data set?"
dataset = gets.chomp
dataset = Array.new
puts 'would you like to add some grades to the array?'
store_grades_response = gets.chomp
while store_grades_response == "y"
puts 'enter grade ->'
grade = gets.chomp.to_i
dataset << grade
puts 'would you like to store another grade?'
store_grades_response = gets.chomp
end
all_data_sets << dataset
puts "would you like to create a new data set?"
create_data_set = gets.chomp
end
end
puts all_data_sets
This way, you keep pushing the datasets into the all_data_sets after each loop.
I hope this is explanatory enough.
Fix
Its because your create new_data_sets array each time you do the loop, declare it outside enclosing while loop
Code
def main
mainDataSet = [] # All datasets
dataSetNames = [] # Incase you want to store data set names
response = getInput("Would you like to save a data set")
if(response == "y")
choice = getInput("Create a new dataset?")
while choice == "y"
dataset = getInput("What do you want to name the data set?")
dataSetNames << dataset
dataset = []
choice_2 = getInput("would you like to add some grades to the array?")
while choice_2== "y"
grade = getInput("Enter grade")
dataset << grade
choice_2 = getInput("Store another grade?")
end
mainDataSet << dataset
choice = getInput("Create a new data set?")
end
end
puts mainDataSet
puts dataSetNames
end
def getInput(message)
puts "#{message} -> "
gets.chomp
end
Hope this helps.
you can concat, prepend or append arrays just like this
dataset.concat all_dataset
dataset + all_dataset
Concat documentation
prepend or append
dataset.push(*all_dataset)
all_dataset.unshift(*dataset)
Array stuffs
Also you can do slice and whole bunch of stuffs check at the ruby docs link

Text file over written and not appended

So far I have this program doing what i want. However when running through it will overwrite the last employee record instead of just adding to the file. I'm new to prgramming and have been staring at this for hours and i can't get it yet. Just need a little nudge in the right direction.
# Define Employee Class
# Common Base Class for all Employees
class EmployeeClass:
def Employee(fullName, age, salary):
fullName = fullName
age = age
salary = salary
def displayEmployee():
print("\n")
print("Name: " + fullName)
print("Age: " + age)
print("Salary: " + salary)
print("\n")
EmployeeArray = []
Continue = True
print ("Employee Information V2.0")
while Continue == True:
print ("Welcome to Employee Information")
print ("1: Add New Record")
print ("2: List Records")
print ("3: Quit")
choice = input("Pick an option: ")
if choice == "1":
fullName = input ("Enter Full Name: ")
if fullName == "":
blankName = input ("Please enter a name or quit: ")
if blankName == "quit":
print ("Goodbye!")
print ("Hope to see you again.")
Continue = False
break
age = input ("Enter Age: ")
salary = input ("Enter Salary: ")
EmployeeRecords = open ('EmployeeRecords.txt' , 'w')
EmployeeRecords.write("Full Name: " + fullName + '\n')
EmployeeRecords.write("Age: " + age + '\n')
EmployeeRecords.write("Salary: " + salary + '\n')
EmployeeRecords.close()
elif choice == "2":
EmployeeRecords = open ('EmployeeRecords.txt', 'r')
data = EmployeeRecords.read()
print ("\n")
print (data)
EmployeeRecords.close
elif choice == "3":
answer = input ("Are you sure you want to quit? " "yes/no: ")
if answer == "yes" or "y":
print ("Bye!")
Continue = False
else:
Continue
else:
print ("Please choose a valid option")
print ("\n")
You are opening the file to be rewritten each time, based on the control string passed to open. Change open ('EmployeeRecords.txt, 'w')to open ('EmployeeRecords.txt', 'a+'). and the records will be appended to the end of the file.
Append mode should work.
EmployeeRecords = open('EmployeeRecords.txt', 'a')

Resources