How to create this gw basic program? - basic

Ok i want to know how to make a sentence appear word by word in GW BASIC.For example if the sentence is I Am Boy then how to make it appear as so "I" comes first printed then "A" ,then "m" , then B and so on....simply like in typing
Plz help me And it will be appreciated if you post a working programme codingg

Here's an example that waits three seonds:
T! = TIMER + 3: WHILE TIMER < T!: WEND

10 cls
20 rem variables go here
30 print A$
40 gosub 500 REM Timer Here
50 print B$
60 gosub 500
etc
510 Otime=val(right$(time$,2))
520 Ntime=val(right$(time$,2))
530 if Ntime-Otime>3 or Ntime-Otime<0 then return else goto 510
This should work, if not, it will lie in the 500 lines and should only need a minor adjustment.

Related

Count pattern matches in paragraphs separated by empty lines in Python

I want to count matches in rows that have a pattern TRP or PHE or MET - I need to count it per paragraph (separated by empty lines). Then I would like to calculate the percentage of the matches by dividing the matches count by the number of lines in each paragraph. Is there a quick python solution for this?
My input looks like:
THR 61 65.21
LEU 62 63.85
PRO 63 54.61
LEU 64 50.74
ALA 65 57.40
PRO 66 56.49
ASP 67 56.77
PRO 68 55.94
TYR 69 56.06
PRO 70 56.55
GLY 71 57.74
HIS 72 55.69
ASN 73 64.70
PRO 74 65.70
ASP 422 65.05
SER 423 53.19
SER 424 45.39
ARG 425 47.80
ALA 426 48.84
ARG 427 46.19
ALA 428 46.81
SER 429 51.64
GLY 430 56.53
GLY 431 69.14
ASP 471 59.01
VAL 472 51.82
ASP 473 52.63
GLN 474 45.86
LEU 475 44.30
SER 476 45.83
LEU 477 45.78
THR 478 37.91
PRO 479 44.77
VAL 480 41.47
VAL 481 46.86
PRO 482 46.12
GLY 483 46.38
PRO 484 49.42
PRO 485 57.74
I tried with awk but it is too hard...
This should do the trick, assuming your input is a txt file.
Even though your input is not a text file you can load the input accordingly.
def calc_percetage(log, line_count):
for pattern, sum in log.items():
percentage[pattern] = (sum/line_count)*100
return percentage
#log = {'TRP': 0, 'THR': 0, 'PRO': 0} This method can be used if number of patterns are less
log =dict()
for patterns in ['TRP', 'THR', 'PRO']:
log[patterns] = 0
para = 1
percentage ={}
count = 0
with open("input.txt") as input_file:
for line in input_file:
count +=1
for pattern, sum in log.items():
if pattern in line:
log[pattern] += 1
if (re.match('\r?\n', line)):
line_count = count -1
print(f"end of para {para} & number of lines {line_count}")
print(f"count from paragraph {para} is {log}")
percentage = calc_percetage(log, line_count)
print(f"percentages are as followed {percentage}")
para = para +1
#reset for next paragraph
count = 0
log = {'TRP': 0, 'THR': 0, 'PRO': 0} #This will change if you use dynamic way to generate the dict called 'log', you can reuse the for loop initially used to create dict
#handaling last paragraph
line_count = count
print(f"end of para {para} & number of lines {line_count}")
print(f"count from paragraph {para} is {log}")
percentage = calc_percetage(log, line_count)
print(f"percentages are as followed {percentage}")
This task is straight forward in awk if the record separator is set to read paragraphs (one or more blank lines between lines) using RS="" (special meaning explained towards the bottom of this page of the awk manual: https://www.gnu.org/software/gawk/manual/html_node/awk-split-records.html), and the field separator is set to read lines as fields using FS="\n". In my example I have set these in a BEGIN block but shell switches could be used also.
Once the fields are configured, pattern blocks are established for each search pattern. The action of each is to increment a counter (action only applied when pattern is present). A final universal block can print the count and the number of fields/lines (NF) for that record, and perform whatever arithmetic is required with them.
awk procedure run on file.txt:
awk ' BEGIN {RS="";FS="\n";} /TRP/{aa++;} /PHE/{aa++} /MET/{aa++} {print "set " NR": " 0+aa " matches in " NF " lines, Ratio=" (0+aa)/NF; aa=0}' file.txt
Note that the patterns are separated into distinct blocks to make sure the counter is incremented more than once for more than one match - if a combined or (|) pattern had been used, the count would only increase once if two matches were present.
output
set 1: 0 matches in 14 lines, Ratio=0
set 2: 0 matches in 10 lines, Ratio=0
set 3: 0 matches in 15 lines, Ratio=0
If totals for the file are required, a second counter variable can be added to each block that is not reset in the last block, along with a counter to accumulate the NF count for each record. In such a case, an END block can be used to sum and calculate overall ratios.

Horizotal print of a complex string block

Once again I'm asking for you advice. I'm trying to print a complex string block, it should look like this:
32 1 9999 523
+ 8 - 3801 + 9999 - 49
---- ------ ------ -----
40 -3800 19998 474
I wrote the function arrange_printer() for the characters arrangement in the correct format that could be reutilized for printing the list. This is how my code looks by now:
import operator
import sys
def arithmetic_arranger(problems, boolean: bool):
arranged_problems = []
if len(problems) <= 5:
for num in range(len(problems)):
arranged_problems += arrange_printer(problems[num], boolean)
else:
sys.exit("Error: Too many problems")
return print(*arranged_problems, end=' ')
def arrange_printer(oper: str, boolean: bool):
oper = oper.split()
ops = {"+": operator.add, "-": operator.sub}
a = int(oper[0])
b = int(oper[2])
if len(oper[0]) > len(oper[2]):
size = len(oper[0])
elif len(oper[0]) < len(oper[2]):
size = len(oper[2])
else:
size = len(oper[0])
line = '------'
ope = ' %*i\n%s %*i\n%s' % (size,a,oper[1],size,b,'------'[0:size+2])
try:
res = ops[oper[1]](a,b)
except:
sys.exit("Error: Operator must be '+' or '-'.")
if boolean == True:
ope = '%s\n%*i' % (ope,size+2, res)
return ope
arithmetic_arranger(['20 + 300', '1563 - 465 '], True)
#arrange_printer(' 20 + 334 ', True)
Sadly, I'm getting this format:
2 0
+ 3 0 0
- - - - -
3 2 0 1 5 6 3
- 4 6 5
- - - - - -
1 0 9 8
If you try printing the return of arrange_printer() as in the last commented line the format is the desired.
Any suggestion for improving my code or adopt good coding practices are well received, I'm starting to get a feel for programming in Python.
Thank you by your help!
The first problem I see is that you use += to add an item to the arranged_problems list. Strings are iterable. somelist += someiterable iterates over the someiterable, and appends each element to somelist. To append, use somelist.append()
Now once you fix this, it still won't work like you expect it to, because print() works by printing what you give it at the location of the cursor. Once you're on a new line, you can't go back to a previous line, because your cursor is already on the new line. Anything you print after that will go to the new line at the location of the cursor, so you need to arrange multiple problems such that their first lines all print first, then their second lines, and so on. Just fixing append(), you'd get this output:
20
+ 300
-----
320 1563
- 465
------
1098
You get a string with \n denoting the start of the new line from each call to arrange_printer(). You can split this output into lines, and then process each row separately.
For example:
def arithmetic_arranger(problems, boolean:bool):
arranged_problems = []
if len(problems) > 5:
print("Too many problems")
return
for problem in problems:
# Arrange and split into individual lines
lines = arrange_printer(problem, boolean).split('\n')
# Append the list of lines to our main list
arranged_problems.append(lines)
# Now, arranged_problems contains one list for each problem.
# Each list contains individual lines we want to print
# Use zip() to iterate over all the lists inside arranged_problems simultaneously
for problems_lines in zip(*arranged_problems):
# problems_lines is e.g.
# (' 20', ' 1563')
# ('+ 300', '- 465') etc
# Unpack this tuple and print it, separated by spaces.
print(*problems_lines, sep=" ")
Which gives the output:
20 1563
+ 300 - 465
----- ------
320 1098
If you expect each problem to have a different number of lines, then you can use the itertools.zip_longest() function instead of zip()
To collect all my other comments in one place:
return print(...) is pretty useless. print() doesn't return anything. return print(...) will always cause your function to return None.
Instead of iterating over range(len(problems)) and accessing problems[num], just do for problem in problems and then use problem instead of problems[num]
Debugging is an important skill, and the sooner into your programming career you learn it, the better off you will be.
Stepping through your program with a debugger allows you to see how each statement affects your program and is an invaluable debugging tool

Print "n" results of a function "n" times

I want to print out a sort of pyramid. User inputs an integer value 'i', and that is displayed i-times.
Like if input=5
1
22
333
4444
55555
I have tried this:
input=5
for i in range(input+1):
print("i"*i)
i=i+1
The result of which is
i
ii
iii
iiii
iiiii
The problem is that (as far as I know), only a string can be printed out 'n' times, but if I take out the inverted commas around "i", it becomes (i*i) and gives out squares:
0
1
4
9
16
25
Is there a simple way around this?
Thanks!
Just convert your int loop varaible to str before building the output string by multiplying:
input = 5
for i in range(1, input+1):
print(str(i) * i)
Try this:
a = 5
for i in range(a): # <-- this causes i to go from 0,1,2,3,...,a-1
print("{}".format(i+1)*(i+1)) # < -- this creates a new string in each iteration ; an alternative would be str(i+1)*(i+1)
i=i+1 # <-- this is unnecessary, i already goes from 0 to a-1 and will be re-created in the next iteration of the loop.
This creates a new string in each iteration of the loop.
Note that for i in range(a) will go through the range by itself. There is no need to additionally increment i at the end. In general it is considered bad practise to change indices you loop over.

Pattern Matching BASIC programming Language and Universe Database

I need to identify following patterns in string.
- "2N':'2N':'2N"
- "2N'-'2N'-'2N"
- "2N'/'2N'/'2N"
- "2N'/'2N'-'2N"
AND SO ON.....
basically i want this pattern if written in Simple language
2 NUMBERS [: / -] 2 NUMBERS [: / -] 2 NUMBERS
So is there anyway by which i could write one pattern which will cover all the possible scenarios ? or else i have to write total 9 patterns and had to match all 9 patterns to string.... and it is not the scenario in my code , i have to match 4, 2 number digits separated by [: / -] to string for which i have towrite total 27 patterns. So for understanding purpose i have taken 3 ,2 digit scenario...
Please help me...Thank you
Maybe you could try something like (Pick R83 style)
OK = X MATCH "2N1X2N1X2N" AND X[3,1]=X[6,1] AND INDEX(":/-",X[3,1],1) > 0
Where variable X is some input string like: 12-34-56
Should set variable OK to 1 if validation passes, else 0 for any invalid format.
This seems to get all your required validation into a single statement. I have assumed that the non-numeric characters have to be the same. If this is not true, the check could be changed to something like:
OK = X MATCH "2N1X2N1X2N" AND INDEX(":/-",X[3,1],1) > 0 AND INDEX(":/-",X[6,1],1) > 0
Ok, I guess the requirement of surrounding characters was not obvious to me. Still, it does not make it much harder. You just need to 'parse' the string looking for the first (I assume) such pattern (if any) in the input string. This can be done in a couple of lines of code. Here is a (rather untested ) R83 style test program:
PROMPT ":"
LOOP
LOOP
CRT 'Enter test string':
INPUT S
WHILE S # "" AND LEN(S) < 8 DO
CRT "Invalid input! Hit RETURN to exit, or enter a string with >= 8 chars!"
REPEAT
UNTIL S = "" DO
*
* Look for 1st occurrence of pattern in string..
CARDNUM = ""
FOR I = 1 TO LEN(S)-7 WHILE CARDNUM = ""
IF S[I,8] MATCH "2N1X2N1X2N" THEN
IF INDEX(":/-",S[I+2,1],1) > 0 AND INDEX(":/-",S[I+5,1],1) > 0 THEN
CARDNUM = S[I,8] ;* Found it!
END ELSE I = I + 8
END
NEXT I
*
CRT CARDNUM
REPEAT
There is only 7 or 8 lines here that actually look for the card number pattern in the source/test string.
Not quite perfect but how about 2N1X2N1X2N this gets you 2 number followed by 1 of any character followed by 2 numbers etc.
This might help:
BIG.STRING ="HELLO TILDE ~ CARD 12:34:56 IS IN THIS STRING"
TEMP.STRING = BIG.STRING
CONVERT "~:/-" TO "*~~~" IN TEMP.STRING
IF TEMP.STRING MATCHES '0X2N"~"2N"~"2N0X' THEN
FIRST.TILDE.POSN = INDEX(TEMP.STRING,"~",1)
CARD.STRING = BIG.STRING[FIRST.TILDE.POSN-2,8]
PRINT CARD.STRING
END

BBC basic variables

Background info for the problem: I am writing a text adventure game where the player has multiple paths to choose at each intersection/ problem.
Problem: I am attempting to use a variable from another path, which may not of been called upon. Is there anyway to call this variable before or skip a line of code?
This is the section of my code I am talking about
38 input "What do you do? 'A' to continue, 'B' to run away" , BAB$
39 if BAB$ == "A" then
40 if BCP$ == "B" then
41 print "The hunters see you return"
42 print "When they ask if you found the prisoner, you respond by saying that you havent seen him"
43 print "The hunters decide that this venture isnt worth it, and decide to leave, taking you with them"
44 wait 30
45 print "You escape shortly after the rest of the group leaves the area"
46 print "You are now a free man"
47 wait 200
48 clear
49 cls
50 goto 100
51 else
52 goto 55
53 endif
Have any questions about my wording? Just ask!
The simplest answer to this question is to just initialise the variable at the start of the program:
BAB$ = ""
BCP$ = ""
That way, when you hit line 40, either BCP$ will have a value of "" or have a value of something else.

Resources