I want to take input like this. Here 2 is number of test cases 4 is number of input in Array respectively.
Here is sample of input.
2
4
1 5 3 2
3
3 2 7
Is this what you're looking for?
test_cases = []
number_of_cases = input ('Enter the number of test cases : ')
for index in range (int (number_of_cases)) :
test_cases.append ([])
prompt = 'Enter the number of digits for test ' + str (index + 1) + ' : '
number_of_digits = input (prompt)
for count in range (int (number_of_digits)) :
prompt = 'Enter test case number ' + str (count + 1) + ' : '
test_cases[index].append (input (prompt))
print (test_cases)
Related
I cannot extract the postal/zip code of a given address cell that comes like this :
"108, avenue du Grand Sud 37 170 CHAMBRAY les TOURS".
I have used :
=RECHERCHE(9^9;--("0"&STXT(A2;MIN(CHERCHE({0.1.2.3.4.5.6.7.8.9};A2&"0 123456789"));LIGNE($1:$100))))
Which sometimes works, sometimes not depending on the street number starting the address (here "108,").
The problem is the space of the pattern "37 170". I would like to remove the blank space in the pattern. Is there a regex way to search this pattern "## ###", and then to remove this poisonous blank space?
Thank you for your tricks.
I have tried this piece of code :
Function toto(r, Optional u = 0)
Application.Volatile
Dim i%, j%, adr$, cp$, loca$, x
x = Split(r)
For i = 0 To UBound(x)
If x(i) Like "#####" Then Exit For
Next
If i > UBound(x) Then
adr = r.Value 'facultatif
Else
cp = x(i)
For j = 0 To i - 1: adr = adr & x(j) & " ": Next
adr = Left$(adr, Len(adr) + (Len(adr) > 1))
For j = i + 1 To UBound(x): loca = loca & x(j) & " ": Next
loca = Left$(loca, Len(loca) + (Len(loca) > 1))
End If
x = Array(adr, cp, loca)
If 0 < u And u < 4 Then toto = x(u - 1) Else toto = x
End Function
The above code works fine for splitting addresses including street number, zip code, and city name. But it does not work when the zip code is ## ### = 2 digit integer - space - 3 digit integer.
Edit: 01 June 2021
Since it seems my question is not clear enough, let's rephrase :
Given an Excel worksheet containing in each cell of column A, from saying A1 down to A10000, complete addresses like this one :
"2 rue Rene cassin Centre Commercial Châlon 2 Sud 71 100 CHALON SUR SAONE"
or this one :
"15, Rue Emile Schwoerer 68 000 COLMAR"
Where "71 100" and "68 000" are a zip code in incorrect format because of the extra space between the 2 first digits and 3 last digits.
I need to split the Ai cell content in order to obtain :
in cell Bi : the text (street, etc.) placed left before the 2 first digits of the "wrong" zip code,
in cell Ci : the zip code with its correct format ("71100" and not "71 100"),
in cell Di : the text (city name) after the zip code.
It's a kind of left and right extraction around the zip code.
The above code that I have posted does not work.
In order to obtain the correct zip code format, I have tried the regex following function :
Function FindReplaceRegex(rng As Range, reg_exp As String, replace As String)
Set myRegExp = New RegExp
myRegExp.IgnoreCase = False
myRegExp.Global = True
myRegExp.Pattern = reg_exp
FindReplaceRegex = myRegExp.replace(rng.Value, replace)
End Function
But I am unable to determine the correct regular expression pattern to get rid of the space in the zip code.
PEH gave me the following pattern :
(.*)([0-9]{2} ?[0-9]{3})(.*)
When using the function, I have tried to define the replacement pattern by:
(.*)([0-9]{2}[0-9]{3})(.*)
But it would not work. Hope this will clarify my question.
Any idea is welcome. Thanks
If these input strings always have the same pattern, try:
=CONCAT(FILTERXML("<t><s>"&SUBSTITUTE(A1," ","</s><s>")&"</s></t>","//s[.*0=0]"))
Depending on your needs/edge-cases, you could add more xpath expressions.
If this is VBA, I have a fix for you (please forgive the crappy naming convention, I'm scribbling this down in work while waiting for SQL to refresh):
Sub test1()
a0 = Cells(1, 1) 'Get the text, in this case "108, avenue du Grand Sud 37 170 CHAMBRAY les TOURS"
aa = Replace(a0, ",", " ") 'Make all delimiters of same type, so removing commas, you may need to add more replace work here?
ab = Application.Trim(aa) 'Reduce all whitespace to single entries, i.e. " " rather than " "
ac = Split(ab, " ", -1) 'Now split by that single whitespace entry
Dim txt()
i2 = 0
lastIsNumeric = False
For i1 = 0 To UBound(ac) - 1 'Step through each entry in our "split" list
If IsNumeric(ac(i1)) = True And IsNumeric(ac(i1 + 1)) = True Then
'Two numbers back to back, join
ReDim Preserve txt(i2)
txt(i2) = ac(i1) + ac(i1 + 1)
i2 = i2 + 1
i1 = i1 + 1
Else
'Not two numbers back to back, don't join
ReDim Preserve txt(i2)
txt(i2) = ac(i1)
i2 = i2 + 1
End If
Next i1
If IsNumeric(ac(UBound(ac))) = False Then
'Need to add last entry to txt()
ReDim Preserve txt(UBound(txt) + 1)
txt(UBound(txt)) = ac(UBound(ac))
End If
End Sub
edit 2021-06-01:
The above will generate a list (txt) of all the entries within your address. You can then reassemble if you wish, or extract out the postcode only.
If you want it as a function, then it would be:
Public Function getPostcode(a0)
aa = Replace(a0, ",", " ")
ab = Application.Trim(aa)
ac = Split(ab, " ", -1)
Dim txt()
i2 = 0
lastIsNumeric = False
For i1 = 0 To UBound(ac) - 1
If IsNumeric(ac(i1)) = True And IsNumeric(ac(i1 + 1)) = True Then
'Two numbers back to back, join
ReDim Preserve txt(i2)
txt(i2) = ac(i1) + ac(i1 + 1)
i2 = i2 + 1
i1 = i1 + 1
Else
'Not two numbers back to back, don't join
ReDim Preserve txt(i2)
txt(i2) = ac(i1)
i2 = i2 + 1
End If
Next i1
If IsNumeric(ac(UBound(ac))) = False Then
'Need to add last entry to txt()
ReDim Preserve txt(UBound(txt) + 1)
txt(UBound(txt)) = ac(UBound(ac))
End If
'Re-assemble string for return
rtnTxt = ""
For i1 = 0 To UBound(txt)
rtnTxt = rtnTxt & " " & txt(i1)
Next i1
getPostcode = rtnTxt
End Function
i need help for my syntax,
i using code:
numbers = 10
for number in range(numbers):
print (number,end="\t")
number += 1
print (number,end="\t")
number += 1
print (number,end="\t")
number += 1
print (number,end="\t")
number += 1
print (number,end="\t")
number += 1
print (number,end="\t")
number += 1
print (number,end="\t")
number += 1
print (number,end="\t")
number += 1
print (number,end="\t")
number += 1
print (number)
I don't know how to shorten the code.
If i use conditional like:
numbers = 10
for number in range(numbers):
print (number,end="\t")
if int(str(numbers)[:1]) != 10:
number += 1
print (number)
elif int(str(numbers)[:1] == 10):
print (number)
It only shows:
Here you go:
numbers = 10
for number in range(numbers):
for i in range(numbers):
print (number,end="\t")
number += 1
print('\n',end='')
You can add nested for loops.
The easy (though definitely not best!) way is to just loop it twice:
numbers = 10
for rowIndex in range(numbers):
rowString = ''
for columnIndex in range(numbers): #Same number of points
#each row is equivalent to the previous row + 1 - use existing iterator
rowString += str(columnIndex + rowIndex) + '\t'
print(rowString)
By way of explanation of what your code's currently doing:
You're converting numbers (i.e. 10) to a string, then taking a substring starting at character zero and ending before character 1. This will always be '1'
You're converting that back to an int (i.e. 1)
You're then comparing that to 10. Since 1 does not equal 10, all you're doing is printing number + 1 after your first print
Something similar would work if you used range(numbers) instead, but without another loop it's still only going to print one more column
You can do the following.
numbers = 10
for number in range(numbers):
print(" ".join([str(index) for index in range(number, numbers + number )]))
So I am using lua and splitting a string by spaces to write a sort of sub-language. And I am trying to have it not split anything inside parenthesis, I am already at the stage where I can detect whether there is parenthesis. But I want to reverse the gmatching of the string inside the parenthesis as I want to preserve the string contained within.
local function split(strng)
local __s={}
local all_included={}
local flag_table={}
local uncompiled={}
local flagged=false
local flagnum=0
local c=0
for i in string.gmatch(strng,'%S+') do
c=c+1
table.insert(all_included,i)
if(flagged==false)then
if(string.find(i,'%('or'%['or'%{'))then
flagged=true
flag_table[tostring(c)]=1
table.insert(uncompiled,i)
print'flagged'
else
table.insert(__s,i)
end
elseif(flagged==true)then
table.insert(uncompiled,i)
if(string.find(i,'%)' or '%]' or '%}'))then
flagged=false
local __=''
for i=1,#uncompiled do
__=__ .. uncompiled[i]
end
table.insert(__s,__)
print'unflagged'
end
end
end
return __s;
end
This is my splitting code
I would just not use gmatch for this at all.
local input = " this is a string (containg some (well, many) annoying) parentheses and should be split. The string contains double spaces. What should be done? And what about trailing spaces? "
local pos = 1
local words = {}
local last_start = pos
while pos <= #input do
local char = string.byte(input, pos)
if char == string.byte(" ") then
table.insert(words, string.sub(input, last_start, pos - 1))
last_start = pos + 1
elseif char == string.byte("(") then
local depth = 1
while depth ~= 0 and pos + 1 < #input do
local char = string.byte(input, pos + 1)
if char == string.byte(")") then
depth = depth - 1
elseif char == string.byte("(") then
depth = depth + 1
end
pos = pos + 1
end
end
pos = pos + 1
end
table.insert(words, string.sub(input, last_start))
for k, v in pairs(words) do
print(k, "'" .. v .. "'")
end
Output:
1 ''
2 'this'
3 'is'
4 'a'
5 'string'
6 '(containg some (well, many) annoying)'
7 'parentheses'
8 'and'
9 'should'
10 'be'
11 'split.'
12 'The'
13 'string'
14 'contains'
15 ''
16 'double'
17 ''
18 ''
19 'spaces.'
20 'What'
21 'should'
22 'be'
23 'done?'
24 'And'
25 'what'
26 'about'
27 'trailing'
28 'spaces?'
29 ''
Thinking about trailing spaces and other such problems is left as an exercise for the reader. I tried to highlight some of the possible problems with the example that I used. Also, I only looked at one kind of parenthesis since I do not want to think how this (string} should be ]parsed.
Oh and if nested parenthesis are not a concerned: Most of the code above can be replaced with a call to string.find(input, ")", pos, true) to find the closing parenthesis.
Please note that you cannot or or and patterns as attempted in your code.
"%(" or "%[" equals "%("
Lua will interpret that expression left to right. "%( is a true value Lua will reduce the expression to "%(", which logically is the same as the full expression.
So string.find(i,'%('or'%['or'%{') will only find ('s in i.
As a similar but slightly different approach to Uli's answer, I would first split by parentheses. Then you can split the the odd-numbered fields on whitespace:
split = require("split") -- https://luarocks.org/modules/telemachus/split
split__by_parentheses = function(input)
local fields = {}
local level = 0
local field = ""
for i = 1, #input do
local char = input:sub(i, i)
if char == "(" then
if level == 0 then
-- add non-parenthesized field to list
fields[#fields+1] = field
field = ""
end
level = level + 1
end
field = field .. char
if char == ")" then
level = level - 1
assert(level >= 0, 'Mismatched parentheses')
if level == 0 then
-- add parenthesized field to list
fields[#fields+1] = field
field = ""
end
end
end
assert(level == 0, 'Mismatched parentheses')
fields[#fields+1] = field
return fields
end
input = " this is a string (containg some (well, many) annoying) parentheses and should be split. The string contains double spaces. What should be done? And what about trailing spaces? "
fields = split__by_parentheses(input)
for i, field in ipairs(fields) do
print(("%d\t'%s'"):format(i, field))
if i % 2 == 1 then
for j, word in ipairs(split.split(field)) do
print(("\t%d\t%s"):format(j, word))
end
end
end
outputs
1 ' this is a string '
1
2 this
3 is
4 a
5 string
6
2 '(containg some (well, many) annoying)'
3 ' parentheses and should be split. The string contains double spaces. What should be done? And what about trailing spaces? '
1
2 parentheses
3 and
4 should
5 be
6 split.
7 The
8 string
9 contains
10 double
11 spaces.
12 What
13 should
14 be
15 done?
16 And
17 what
18 about
19 trailing
20 spaces?
21
The program requires input of positive numbers, and counts each even number using a loop function that doesn't count odds and ends if a O is input.
I'm not sure how to go about creating a loop or if I can use an if function within the loop.
Dim Count = 0
While (number mod 2 = 0) do
Count + 1 = Count
I actually didn't understand the question very well but as far as concerned, if you dont want odd numbers to be included I suggest on count add 2 not one , since the count variable starts with zero do:
Dim Count+2
Btw when do you want the count to stop? At 2 And goes back to 0?
If so then use the if statement
var Dim_count = 0;
if(Dim_count == 0){Dim_count+2}
else if(Dim_count ==2){Dim_Count =0;}
It would help if you provide a sample input so we can work with actual code and guide you to the right solution.
If you receive the input as, let's say, array of numbers, you can simply loop trough it using for or foreach and add additional condition to check for 0 if you want to preliminary exit:
For Each number As Integer In numbers
If (number mod 2 = 0) Then
Count = Count + 1
End If
If (number = 0) Then
Exit For
End If
Next
If you have existing code in which somehow number is reinitialized/redefined on each iteration already, then what you have is pretty close to what you need:
While (number <> 0)
If (number mod 2 = 0) Then
Count = Count + 1
End If
End While
Function counts even numbers:
REM function gets input, exits at 0 and adds positive even numbers.
DO
INPUT X
IF X = 0 THEN PRINT Y; " even numbers": END
IF X > 0 THEN
IF X / 2 = X \ 2 THEN Y = Y + 1
END IF
LOOP
I am completely unsure about this. just a guess...
Dim j as Integer
Dim i As integer
j = 0
i = 2
For i = 1 to 100
j = j+i
Print j
Loop
End Sub
Assuming you are getting numbers from some input, this is how you can do it. Have an infinite loop with While True, then for every number given from your input, check if its even using number mod 2 = 0. This will go on forever so you need to add some condition (another if statement) for it to stop the while loop. More information about while loops here: https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/while-end-while-statement
Dim Count = 0
While True do
If (number mod 2 = 0) Then
Count + 1 = Count
End If
End While
I am taking a computer sciences class right now, and I just have no idea how to convert an average made from 3 scores to a letter grade. At first I thought I could do something like:
PRINT name$(c); TAB(6) ; USING("###.#", average(c))
As:
PRINT name$(c); TAB(6) ; USING("***something for text here***", average(c))
But after my searches and scouring on the internet, I came up with nothing. After a while I rewrote a majority of my code, but it still doesnt work correctly. Can someone tell me what I can do to get it working?
Here it is:
dim names(20)
dim average$(20)
x = 0
input "Please input Teacher's name:"; teacher$
rem teacher$
cls
input "Input student's name:"; studentname$
do while studentname$ <> ""
name$(x)=studentname$
rem name$(x)
input "Input first number:"; e
input "Input second number:"; f
input "Input third number:"; g
avg$=(e+f+g)/3
average(x)= avg
x=x+1
cls
input "Input the next name or press enter to finish:"; studentname$
loop
print teacher$; "'s Class Report"
for c = 1 to X
if (avg$>89 and avg$<101) then let avg= "A" else if
if (avg$>79 and avg$<89) then let avg= "B" else if
if (avg$>69 and avg$<79) then let avg= "C" else if
if (avg$>59 and avg$<69) then let avg= "D" else if
if (avg$<59) then let avg= "F"; print names(c), TAB(6) average$(c)
next c
end
Three thing to note here.
First off, the dollar sign $ is only used at the end of variablenames that contain text values not numeric values. So it's a$ = "hello" and i = (12+34+56) / 3 etc.
Secondly, in the input part you calculate the average value and store it in variable avg$. Then in the for-loop where you want to print the letter grades you check the same variable name. However, you never set avg$ within that for-loop, so it will always just contain the last calculated value. And also it should be without $ because it's a numeric value.
Finally, like Shawn Mehan also already commented, you should rename your variables to better reflect what they are used for. That will probably clear up some of the confusion. So something like dim avgpoint(20) for the 0-100 scores, and avgletter$="A" etc. for the letters grade.
So to combine these things, I would change your code to something like this:
input "Input first grade number (0-100):"; grade1
input "Input second grade number (0-100):"; grade2
input "Input third grade number (0-100):"; grade3
calcavg = (grade1+grade2+grade3)/3
avgpoint(x) = calcavg
and then
for c = 1 to x
p = avgpoint(x)
if (p>89 and p<=101) then let avgletter$ = "A"
'etc.
Here is some coding sample for a grade report program:
DIM Names(20) AS STRING
DIM Average(20) AS SINGLE
INPUT "Please input Teacher's name"; Teacher$
PRINT "Enter up to 20 names, <enter> to quit:"
DO UNTIL x = 20
PRINT "Input student"; x + 1; "name";
INPUT StudentName$
IF StudentName$ = "" THEN EXIT DO
x = x + 1: Names(x) = StudentName$
INPUT "Input first number"; J
INPUT "Input second number"; K
INPUT "Input third number"; L
Average(x) = (J + K + L) / 3
LOOP
PRINT Teacher$; "'s Class Report"
FOR c = 1 TO x
SELECT CASE Average(c)
CASE 0 TO 59
Grade$ = "F"
CASE 60 TO 69
Grade$ = "D"
CASE 70 TO 79
Grade$ = "C"
CASE 80 TO 89
Grade$ = "B"
CASE ELSE
Grade$ = "A"
END SELECT
PRINT Names(c); SPC(6); Grade$
NEXT
END
Another coding sample of a grade report program with variable number of scores:
DIM Names(20) AS STRING
DIM Average(20) AS SINGLE
INPUT "Please input Teacher's name"; Teacher$
PRINT "Enter up to 20 names, <enter> to quit:"
DO UNTIL x = 20
PRINT "Input student"; x + 1; "name";
INPUT StudentName$
IF StudentName$ = "" THEN EXIT DO
x = x + 1: Names(x) = StudentName$
y = 0 ' number of scores
z = 0 ' total of scores
PRINT "Enter scores, <enter> to quit:"
DO
PRINT "Enter score"; y + 1;
INPUT I$
IF I$ = "" THEN EXIT DO
IF VAL(I$) >= 0 AND VAL(I$) <= 100 THEN
y = y + 1
z = z + VAL(I$)
ELSE
PRINT "Value must be 0 to 100."
END IF
LOOP
IF y > 0 THEN ' avoid division by zero
Average(x) = z / y
END IF
LOOP
PRINT Teacher$; "'s Class Report"
FOR c = 1 TO x
SELECT CASE Average(c)
CASE 0 TO 59
Grade$ = "F"
CASE 60 TO 69
Grade$ = "D"
CASE 70 TO 79
Grade$ = "C"
CASE 80 TO 89
Grade$ = "B"
CASE ELSE
Grade$ = "A"
END SELECT
PRINT Names(c); SPC(6); Grade$
NEXT
END