Skip to content

Instantly share code, notes, and snippets.

@BlueNexus
Last active May 10, 2024 11:05
Show Gist options
  • Save BlueNexus/599962d03a1b52a8d5f595dabd51dc34 to your computer and use it in GitHub Desktop.
Save BlueNexus/599962d03a1b52a8d5f595dabd51dc34 to your computer and use it in GitHub Desktop.
Python to Pseudocode converter
import os.path
import re
'''
INSTRUCTIONS
1. Create a file with the following code
2. Put the file you want to convert into the same folder as it, and rename it to "py_file.py"
3. Add a "#F" comment to any lines in the code which have a function call that doesn't assign anything (so no =),
as the program cannot handle these convincingly
4. Run the converter file
'''
python_file = 'py_file.py'
basic_conversion_rules = {"for": "FOR", "=": "TO", "if": "IF", "==": "EQUALS", "while": "WHILE", "until": "UNTIL",
"import": "IMPORT", "class": "DEFINE CLASS", "def": "DEFINE FUNCTION", "else:": "ELSE:",
"elif": "ELSEIF", "except:": "EXCEPT:", "try:": "TRY:", "pass": "PASS", "in": "IN"}
prefix_conversion_rules = {"=": "SET ", "#F": "CALL "}
advanced_conversion_rules = {"print": "OUTPUT", "return": "RETURN", "input": "INPUT"}
def l2pseudo(to_pseudo):
for line in to_pseudo:
line_index = to_pseudo.index(line)
line = str(line)
line = re.split(r'(\s+)', line)
for key, value in prefix_conversion_rules.items():
if key in line:
if not str(line[0]) == '':
line[0] = value + line[0]
else:
line[2] = value + line[2]
for key, value in basic_conversion_rules.items():
for word in line:
if key == str(word):
line[line.index(word)] = value
for key, value in advanced_conversion_rules.items():
for word in line:
line[line.index(word)] = word.replace(key, value)
for key, value in prefix_conversion_rules.items():
for word in line:
if word == key:
del line[line.index(word)]
to_pseudo[line_index] = "".join(line)
return to_pseudo
def p2file(to_file):
py_file = os.path.splitext(os.path.basename(python_file))[0]
with open(py_file + '_pseudo.txt', 'w') as writer:
writer.write("\n".join(to_file))
def main():
with open(python_file, 'r+') as py_file_reader:
file_lines = py_file_reader.readlines()
work_file = l2pseudo(file_lines)
p2file(work_file)
if __name__ == '__main__':
main()
@Tuhin-thinks
Copy link

@BlueNexus Awesome!! Good to see you have added it!

@parshvibid
Copy link

import os

File to store the readings

file_path = "bp_readings.txt"

Function to record a new blood pressure reading

def record_reading(upper, lower):
with open(file_path, 'a') as file:
file.write(f"{upper},{lower}\n")

Function to calculate the current average of all readings

def calculate_average():
if not os.path.exists(file_path):
return None, None

with open(file_path, 'r') as file:
    lines = file.readlines()
    if not lines:
        return None, None
    
    total_upper, total_lower = 0, 0
    for line in lines:
      values = line.strip().split(",")
if len(values)>= 2:
    upper,lower=map(int,values)
    total_upper += upper
    total_lower += lower
    
    avg_upper = total_upper / len(lines)
    avg_lower = total_lower / len(lines)
    return avg_upper, avg_lower

calculate_average()

Function to display all readings recorded so far

def display_readings():
readings = []
if not os.path.exists(file_path):
return readings

with open(file_path, 'r') as file:
    lines = file.readlines()
    for line in lines:
        upper, lower=map(int,line.strip().split(","))
        readings.append((upper, lower))
return readings

display_readings()

def main_interface():
while True:
print("\nBlood Pressure Recorder")
print("1. Record a new blood pressure reading")
print("2. Calculate the current average of all readings")
print("3. See all the readings recorded so far")
print("4. Exit")

    choice = input("Enter your choice (1/2/3/4): ")
    
    if choice == "1":
        upper = int(input("Enter the upper number: "))
        lower = int(input("Enter the lower number: "))
        record_reading(upper, lower)
        print("Reading recorded successfully!")
    
    elif choice == "2":
        avg_upper, avg_lower = calculate_average()
        if avg_upper is None:
            print("No readings found!")
        else:
            print(f"Average Upper Reading: {avg_upper:.2f}")
            print(f"Average Lower Reading: {avg_lower:.2f}")
    
    elif choice == "3":
        readings = display_readings()
        if not readings:
            print("No readings found!")
        else:
            print("\nRecorded Readings:")
            for upper, lower in readings:
                print(f"Upper: {upper}, Lower: {lower}")
    
    elif choice == "4":
        print("Goodbye!")
        break
    
    else:
        print("Invalid choice! Please select a valid option.")

Let's run the interface to see how it works

For the sake of this platform, we'll not execute the infinite loop here, but the code provided will work outside.

Uncomment the line below to run the interface:

main_interface()

can u pls convert this to pseudocode

@BlueNexus
Copy link
Author

import os

File to store the readings

file_path = "bp_readings.txt"

Function to record a new blood pressure reading

def record_reading(upper, lower): with open(file_path, 'a') as file: file.write(f"{upper},{lower}\n")

Function to calculate the current average of all readings

def calculate_average(): if not os.path.exists(file_path): return None, None

with open(file_path, 'r') as file:
    lines = file.readlines()
    if not lines:
        return None, None
    
    total_upper, total_lower = 0, 0
    for line in lines:
      values = line.strip().split(",")
if len(values)>= 2:
    upper,lower=map(int,values)
    total_upper += upper
    total_lower += lower
    
    avg_upper = total_upper / len(lines)
    avg_lower = total_lower / len(lines)
    return avg_upper, avg_lower

calculate_average()

Function to display all readings recorded so far

def display_readings(): readings = [] if not os.path.exists(file_path): return readings

with open(file_path, 'r') as file:
    lines = file.readlines()
    for line in lines:
        upper, lower=map(int,line.strip().split(","))
        readings.append((upper, lower))
return readings

display_readings()

def main_interface(): while True: print("\nBlood Pressure Recorder") print("1. Record a new blood pressure reading") print("2. Calculate the current average of all readings") print("3. See all the readings recorded so far") print("4. Exit")

    choice = input("Enter your choice (1/2/3/4): ")
    
    if choice == "1":
        upper = int(input("Enter the upper number: "))
        lower = int(input("Enter the lower number: "))
        record_reading(upper, lower)
        print("Reading recorded successfully!")
    
    elif choice == "2":
        avg_upper, avg_lower = calculate_average()
        if avg_upper is None:
            print("No readings found!")
        else:
            print(f"Average Upper Reading: {avg_upper:.2f}")
            print(f"Average Lower Reading: {avg_lower:.2f}")
    
    elif choice == "3":
        readings = display_readings()
        if not readings:
            print("No readings found!")
        else:
            print("\nRecorded Readings:")
            for upper, lower in readings:
                print(f"Upper: {upper}, Lower: {lower}")
    
    elif choice == "4":
        print("Goodbye!")
        break
    
    else:
        print("Invalid choice! Please select a valid option.")

Let's run the interface to see how it works

For the sake of this platform, we'll not execute the infinite loop here, but the code provided will work outside.

Uncomment the line below to run the interface:

main_interface()

can u pls convert this to pseudocode

Are you unable to run the tool in the gist? There are instructions at the top.

@parshvibid
Copy link

where

@BlueNexus
Copy link
Author

where

Copy the code from the top of this page into a .py file, and perform the following instructions:

  1. Create a file with the provided code
  2. Put the file you want to convert into the same folder as it, and rename it to "py_file.py"
  3. Add a "#F" comment to the end of any lines in the code which have a function call that doesn't assign anything (so no =),
    as the program cannot handle these convincingly
  4. Run the converter file

@sALkaldy
Copy link

Please can u help me to convert this cod into pseudcode

def printNGE(arr):
#prepare stack
s = list()
n = len(arr)
arr1 = [0 for i in range(n)]

for i in range(n - 1, -1, -1): 
	while (len(s) > 0 and s[-1] <= arr[i]:
		s.pop()
	if (len(s) == 0):
		arr1[i] = arr[i]	
	else:
		arr1[i] = s[-1]+arr[i]	 
	s.append(arr[i])

print(arr1)

arr = [7,4,5,10,2,1,7,8,2]
n = len(arr)
printNGE(arr)

@Echowe
Copy link

Echowe commented Jan 8, 2024

help me convert to pseudocode please

@Echowe
Copy link

Echowe commented Jan 8, 2024

def check_num_length(list,minimum):
count=0
for i in list:
if i.isdigit():
count += 1
if count>1 and len(list)>=minimum:
return True
else:
return False

def check_uppercase(list):
upper_count=0
for e in list:
if e.isupper():
upper_count+= 1
if upper_count>2:
return True
else:
return False

def check_lowercase(list):
lower_count=0
for o in list:
if o.islower():
lower_count+=1
if lower_count>2:
return True
else:
return False
minim=int(input("Minimum letters required?(has to be over 9)"))
while True:
lst=[]
txt=(input("Password?"))
for t in txt:
lst.append(t)
if check_num_length(lst,minim)==True and check_uppercase(lst)==True and check_lowercase(lst)==True:
print("Strong password")
break
else:
print("Weak password try again, the criterias are uppercase letters>2 lowercase letters>2 numbers>2 and the minimum length should be", minim)

@bsacm
Copy link

bsacm commented Mar 23, 2024

0_0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment