Letter game challenge - Visual basics help- - visual-studio-2017

A word game awards points for the letters used in a word. The lower the frequency of the letter in the English language, the higher the score for the letter. Write a program that asks the user to input a word. The program should then output the score for the word according to the following rule:
https://i.stack.imgur.com/Fhyli.jpg
**and i have done **
Sub Main()
Dim total As Integer
Dim word As String
total = 0
Console.Write("Word:")
word = Console.ReadLine()
Select Case word
Case = "e"
total = total + 1
Case = "a"
total = total + 2
Case = "r"
total = total + 3
Case = "i"
total = total + 4
Case = "o"
total = total + 5
Case = "t"
total = total + 6
Case = "n"
total = total + 7
Case = "s"
total = total + 8
Case = "l"
total = total + 9
Case = "c"
total = total + 10
Case = "u"
total = total + 11
Case = "d"
total = total + 12
Case = "p"
total = total + 13
Case = "m"
total = total + 14
Case = "h"
total = total + 15
Case "g"
total = total + 16
Case = "b"
total = total + 17
Case = "f"
total = total + 18
Case = "y"
total = total + 19
Case = "w"
total = total + 20
Case = "k"
total = total + 21
Case = "v"
total = total + 22
Case = "x"
total = total + 23
Case = "z"
total = total + 24
Case = "j"
total = total + 25
Case = "q"
total = total + 26
End Select
Console.WriteLine(total)
Console.ReadLine()
but the output is 0 i was wondering how to take the full word into account and how to consider for multiple letters in 1 word.

It's simple, Create a dictionary that contains letters and points when form is loaded.
Create a function that returns point value of letter, loop over string with for each loop.
You need a textbox, button and a label.
Dim WordPoints As New Dictionary(Of String, Integer)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
WordPoints.Add("e", 1)
WordPoints.Add("a", 2)
WordPoints.Add("r", 3)
WordPoints.Add("i", 4)
WordPoints.Add("o", 5)
WordPoints.Add("t", 6)
WordPoints.Add("n", 7)
WordPoints.Add("s", 8)
WordPoints.Add("l", 9)
WordPoints.Add("c", 10)
WordPoints.Add("u", 11)
WordPoints.Add("d", 12)
WordPoints.Add("p", 13)
WordPoints.Add("m", 14)
WordPoints.Add("h", 15)
WordPoints.Add("g", 16)
WordPoints.Add("b", 17)
WordPoints.Add("f", 18)
WordPoints.Add("y", 19)
WordPoints.Add("w", 20)
WordPoints.Add("k", 21)
WordPoints.Add("v", 22)
WordPoints.Add("x", 23)
WordPoints.Add("z", 24)
WordPoints.Add("j", 25)
WordPoints.Add("q", 26)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim TotalPoints As Integer
For Each letter As String In TextBox1.Text.ToLower
TotalPoints += WordPoints(letter)
Next
Label1.Text = TotalPoints.ToString
End Sub
What you need to add is some more handling to textbox so it doesn't accept space, numbers and special characters.
And to customize it however you want.

Related

How do I compare two lists to a python tuple, identify items, and append value based on conditionals?

How do I:
Identify which item from the dataframe df falls within each list (list1 or list2)
Create a new column ('new_item')
Determine which variable should be appended to the 'item' value and add it to the new column
Two lists of unique items:
list1 = ['one','two','shoes']
list2 = ['door','four','tires']
If item is in list1, append the following variable value to the end of the item and append it to the 'new_item' column:
twentysix_above = '_26+' (value is equal or greater than 26)
six_to_twentyfive = '_25' (value is between 6 and 25)
one_to_five = '_5' (value is between 1 and 5)
If item is in list2, append the following variable value to the end of each item and append it to the 'new_item' column:
twentyone_above = '_21+' (value is equal or greater than 21)
one_to_twenty = '_20' (value is between 1 and 20)
If the item isn't in either list, carry over the item name to the 'new_item' column.
Dataframe column will have one, some, or none of the 'items' from each list in it and an associated number from the 'number' column. I've gotten partially there, but I'm not sure how to compare to the other list and put that all into the 'new_item' column? Any help is appreciated, thanks!
>> print df
item number
0 one 4
1 door 55
2 sun 2
3 tires 62
4 tires 7
5 water 94
>> list1 = ['one','two','shoes']
>> list2 = ['door','four','tires']
>> df['match'] = df.item.isin(list1)
>> bucket = []
>> for row in df.itertuples():
if row.match == True and row.item > 25:
bucket.append(row.item + '_26+')
elif row.match == True and row.item >5:
bucket.append(row.item + '_25')
elif row.match == True and row.item >0:
bucket.append(row.item +'_5')
else:
bucket.append(row.item)
df['new_item'] = bucket
>> print df
item number match new_item
0 one 4 True one_5
1 door 55 True door
2 sun 2 False sun
3 tires 62 True tires
4 tires 7 True tires
5 water 94 False water
Desired Result: (comparing both lists and potentially not needing the boolean check column)
item number new_item
0 one 4 one_20
1 door 55 door__21+
2 sun 2 sun
3 tires 62 tires_21
4 tires 7 tires_20
5 water 94 water
It looks like your desired result is a bit off. The first row is in list one and has a value of 4, so it should be 'one_5' right?
Anyway, this can be accomplished with boolean masking. DataFrames have a useful isin() function making it easy to find if the value is in your lists. Then you have two more conditions, if you need a value between two numbers, or just one more condition if the range is unbounded.
import pandas as pd
import numpy as np
df = pd.DataFrame({'item': ['one', 'door', 'sun', 'tires', 'tires', 'water'],
'number': [4, 55, 2, 62, 7, 94]})
list1 = ['one','two','shoes']
list2 = ['door','four','tires']
df['new_item'] = df['item']
logic1 = np.logical_and(df.item.isin(list1), df.number > 25)
logic2 = np.logical_and.reduce([df.item.isin(list1), df.number > 5, df.number <= 25])
logic3 = np.logical_and.reduce([df.item.isin(list1), df.number > 1, df.number <= 5])
logic4 = np.logical_and(df.item.isin(list2), df.number >= 21)
logic5 = np.logical_and.reduce([df.item.isin(list2), df.number > 1, df.number < 20])
df.loc[logic1,'new_item'] = df.loc[logic1,'item']+'_26+'
df.loc[logic2,'new_item'] = df.loc[logic2,'item']+'_25'
df.loc[logic3,'new_item'] = df.loc[logic3,'item']+'_5'
df.loc[logic4,'new_item'] = df.loc[logic4,'item']+'_21+'
df.loc[logic5,'new_item'] = df.loc[logic5,'item']+'_20'
And we have this as the output

vlookup function rounding up in vba

Does it exist a way to avoid getting a rounded up result when using vlookup formula in vba. Here is my code:
Sub test()
Dim lastrow, pressurecolumn, lastcolumn As String, total As Integer, x, row, irow, column As Double
lastrow = Range("B8").End(xlDown).Value + 7
Range("Pump_design[Total Pipe losses from plantroom]").ClearContents
For Each row In Columns("EZ")
For irow = 8 To lastrow
total = 0
For column = 4 To 153
x = Cells(irow, column).Value
If Not IsEmpty(x) Then
total = total + Application.WorksheetFunction.VLookup(x, Sheets("Pump Design").Range("Pump_design"), 154, False)
End If
Next column
Cells(irow, "EZ") = Round(total, 4)
If Cells(irow, "EZ") = 0 Then Cells(irow, "EZ").ClearContents
Next irow
row = irow + 1
Next row
End Sub
Just found the trick get total as double instead of integer

Split string of digits into individual cells, including digits within parentheses/brackets

I have a column where each cell has a string of digits, ?, -, and digits in parentheses/brackets/curly brackets. A good example would be something like the following:
3????0{1012}?121-2[101]--01221111(01)1
How do I separate the string into different cells by characters, where a 'character' in this case refers to any number, ?, -, and value within the parentheses/brackets/curly brackets (including said parentheses/brackets/curly brackets)?
In essence, the string above would turn into the following (spaced apart to denote a separate cell):
3 ? ? ? ? 0 {1012} ? 1 2 1 - 2 [101] - - 0 1 2 2 1 1 1 1 (01) 1
The amount of numbers within the parentheses/brackets/curly brackets vary. There are no letters in any of the strings.
Here you are!
RegEx method:
Sub Test_RegEx()
Dim s, col, m
s = "3????0{1012}?121-2[101]--01221111(01)1"
Set col = CreateObject("Scripting.Dictionary")
With CreateObject("VBScript.RegExp")
.Global = True
.Pattern = "(?:\d|-|\?|\(\d+\)|\[\d+\]|\{\d+\})"
For Each m In .Execute(s)
col(col.Count) = m
Next
End With
MsgBox Join(col.items) ' 3 ? ? ? ? 0 {1012} ? 1 2 1 - 2 [101] - - 0 1 2 2 1 1 1 1 (01) 1
End Sub
Loop method:
Sub Test_Loop()
Dim s, col, q, t, k, i
s = "3????0{1012}?121-2[101]--01221111(01)1"
Set col = CreateObject("Scripting.Dictionary")
q = "_"
t = True
k = 0
For i = 1 To Len(s)
t = (t Or InStr(1, ")]}", q) > 0) And InStr(1, "([{", q) = 0
q = Mid(s, i, 1)
If t Then k = k + 1
col(k) = col(k) & q
Next
MsgBox Join(col.items) ' 3 ? ? ? ? 0 {1012} ? 1 2 1 - 2 [101] - - 0 1 2 2 1 1 1 1 (01) 1
End Sub
Something else to look at :)
Sub test()
'String to parse through
Dim aStr As String
'final string to print
Dim finalString As String
aStr = "3????0{1012}?121-2[101]--01221111(01)1"
'Loop through string
For i = 1 To Len(aStr)
'The character to look at
char = Mid(aStr, i, 1)
'Check if the character is an opening brace, curly brace, or parenthesis
Dim result As String
Select Case char
Case "["
result = loop_until_end(Mid(aStr, i + 1), "]")
i = i + Len(result)
result = char & result
Case "("
result = loop_until_end(Mid(aStr, i + 1), ")")
i = i + Len(result)
result = char & result
Case "{"
result = loop_until_end(Mid(aStr, i + 1), "}")
i = i + Len(result)
result = char & result
Case Else
result = Mid(aStr, i, 1)
End Select
finalString = finalString & result & " "
Next
Debug.Print (finalString)
End Sub
'Loops through and concatenate to a final string until the end_char is found
'Returns a substring starting from the character after
Function loop_until_end(aStr, end_char)
idx = 1
If (Len(aStr) <= 1) Then
loop_until_end = aStr
Else
char = Mid(aStr, idx, 1)
Do Until (char = end_char)
idx = idx + 1
char = Mid(aStr, idx, 1)
Loop
End If
loop_until_end = Mid(aStr, 1, idx)
End Function
Assuming the data is in column A starting in row 1 and that you want the results start in column B and going right for each row of data in column A, here is alternate method using only worksheet formulas.
In cell B1 use this formula:
=IF(OR(LEFT(A1,1)={"(","[","{"}),LEFT(A1,MIN(FIND({")","]","}"},A1&")]}"))),IFERROR(--LEFT(A1,1),LEFT(A1,1)))
In cell C1 use this formula:
=IF(OR(MID($A1,SUMPRODUCT(LEN($B1:B1))+1,1)={"(","[","{"}),MID($A1,SUMPRODUCT(LEN($B1:B1))+1,MIN(FIND({")","]","}"},$A1&")]}",SUMPRODUCT(LEN($B1:B1))+1))-SUMPRODUCT(LEN($B1:B1))),IFERROR(--MID($A1,SUMPRODUCT(LEN($B1:B1))+1,1),MID($A1,SUMPRODUCT(LEN($B1:B1))+1,1)))
Copy the C1 formula right until it starts giving you blanks (there are no more items left to split out from the string in the A cell). In your example, need to copy it right to column AA. Then you can copy the formulas down for the rest of your Column A data.

if statement on discount

A_quantity = 10
B_quantity = 20
the quantity amount
N = float (input('please enter the quantity of package: '))
X_total = float (N*99.00)
the fee from input
Q_discount = (0.2*X_total)
W_discount = (X_total*0.3)
discounts from input total
Y_total = (X_total-Q_discount)
M_total = (X_total-W_discount)
the fee with the discount
def main ():
if N >= A_quantity:
print ('the total cost is $', \
format (Y_total, ',.2f'))
else:
if N >= B_ quantity:
print ('the total cost is $', \
format (M_total, ',.2f'))
main ()
the results should be 10 packages for $792.00
and 20 packages for $1,380.00
yet the second statement gets the 20% discount also which total to $1549.00, when it should get only 30% discount
I don't know which language it is, but it's an algorithm problem : you should first try for the highest value cause the way it is designed now, if N = 30 , you will always enter the "if" , never the "else" , and if N=5 , you will enter the "else" , but the the if inside it...
let me try although I don't know the language:
def main ():
if N >= B_quantity:
print ('the total cost is $', \
format (M_total, ',.2f'))
else:
if N >= A_quantity:
print ('the total cost is $', \
format (Y_total, ',.2f'))
main ()
take the value of the product divided by 100 and multiplied by the discount
and then get this result and the value of the product subitrair
var SomaPercent = ValorUnit/100 * descont;
var result_fim = ValorUnit-SomaPercent;
you can change the if condition to
if N >= A_quantity && N < B_quantity ...
if N >= B_quantity
..

How do I take already calculated totals that are in a loop and add them together?

I created this program in Python 2.7.3
I did this in my Computer Science class. He assigned it in two parts. For the first part we had to create a program to calculate a monthly cell phone bill for five customers. The user inputs the number of texts, minutes, and data used. Additionaly, there are overage fees. $10 for every GB of data over the limit, $.4, per minute over the limit, and $.2 per text sent over the limit. 500 is the limit amount of text messages, 750 is the limit amount of minutes, and 2 GB is the limit amount of data for the plan.
For part 2 of the assignment. I have to calculate the total tax collected, total charges (each customer bill added together), total goverment fees collected, total customers who had overages etc.
Right now all I want help on is adding the customer bills all together. As I said earlier, when you run the program it prints the Total bill for 5 customers. I don't know how to assign those seperate totals to a variable, add them together, and then eventually print them as one big variable.
TotalBill = 0
monthly_charge = 69.99
data_plan = 30
minute = 0
tax = 1.08
govfees = 9.12
Finaltext = 0
Finalminute = 0
Finaldata = 0
Finaltax = 0
TotalCust_ovrtext = 0
TotalCust_ovrminute = 0
TotalCust_ovrdata = 0
TotalCharges = 0
for i in range (1,6):
print "Calculate your cell phone bill for this month"
text = input ("Enter texts sent/received ")
minute = input ("Enter minute's used ")
data = input ("Enter Data used ")
if data > 2:
data = (data-2)*10
TotalCust_ovrdata = TotalCust_ovrdata + 1
elif data <=2:
data = 0
if minute > 750:
minute = (minute-750)*.4
TotalCust_ovrminute = TotalCust_ovrminute + 1
elif minute <=750:
minute = 0
if text > 500:
text = (text-500)*.2
TotalCust_ovrtext = TotalCust_ovrtext + 1
elif text <=500:
text = 0
TotalBill = ((monthly_charge + data_plan + text + minute + data) * (tax)) + govfees
print ("Your Total Bill is... " + str(round(TotalBill,2)))
print "The toatal number of Customer's who went over their minute's usage limit is... " ,TotalCust_ovrminute
print "The total number of Customer's who went over their texting limit is... " ,TotalCust_ovrtext
print "The total number of Customer's who went over their data limit is... " ,TotalCust_ovrdata
Some of the variables created are not used in the program. Please overlook them.
As Preet suggested.
create another variable like TotalBill i.e.
AccumulatedBill = 0
Then at the end of your loop put.
AccumulatedBill += TotalBill
This will add each TotalBill to Accumulated. Then simply print out the result at the end.
print "Total for all customers is: %s" %(AccumulatedBill)
Note: you don't normally use uppercase on variables for the first letter of the word. Use either camelCase or underscore_separated.