def main(): if len(sys.argv) != 2: print("Usage: caesar.py key") sys.exit(1) try: k = int(float(sys.argv[1])) if k < 0: raise ValueError except: print("Key must be a non-negative integer") sys.exit(2) print("plaintext: ", end='') plaintext = cs50.get_string() print("ciphertext: ", end='') for c in plaintext: if c.isalpha(): if c.islower(): alpha_shift = 97 elif c.isupper(): alpha_shift = 65 print(chr(alpha_shift + ((ord(c) - alpha_shift + k) % 26)), end='') else: print(c, end='') print()
def main(): if len(sys.argv) != 2: print("Usage: vigenere.py <key>") sys.exit(1) if not sys.argv[1].isalpha(): print("Key must be an alphabetic string.") sys.exit(2) key_cycle = cycle([(ord(x) - 65) for x in sys.argv[1].upper()]) print("plaintext: ", end='') plaintext = cs50.get_string() print("ciphertext: ", end='') for c in plaintext: if c.isalpha(): if c.islower(): alpha_shift = 97 elif c.isupper(): alpha_shift = 65 print(chr(alpha_shift + ((ord(c) - alpha_shift + next(key_cycle)) % 26)), end='') else: print(c, end='') print()
def main(): if len(sys.argv) != 2: print("You should provide cmd line arguments!") exit(1) key = int(sys.argv[1]) translated = [] message = cs50.get_string() for symbol in message: if symbol.isalpha(): translated.append(caesar(symbol, key)) else: translated.append(symbol) print("".join(translated)) exit(0)
def main(): if(len(sys.argv) != 2 or not(allAlpha(sys.argv[1]))): eprint("Usage: python vigenere k") sys.exit(1) k = list(sys.argv[1]) for i in range(len(k)): if (k[i].isupper()): k[i] = (ord(k[i]) - ord('A')) else: k[i] = (ord(k[i]) - ord('a')) text = get_string("plaintext: ") count = 0 for i in range(len(text)): if(text[i].isalpha()): if(text[i].isupper()): text = text[:i] + chr(((ord(text[i]) - ord('A') + k[count]) % 26) + ord('A')) + text[i + 1:] else: text = text[:i] + chr(((ord(text[i]) - ord('a') + k[count]) % 26) + ord('a')) + text[i + 1:] count = (count + 1) % len(k) print("ciphertext: {0}".format(text))
def main(): if len(sys.argv) != 2: print("You should provide a cmd line arguments!") exit(1) if sys.argv[1].isalpha() == False: print("You should provide valid keyword!") exit(1) message = cs50.get_string() translated = [] keyIndex = 0 keylength = len(sys.argv[1]) for symbol in message: if symbol.isalpha(): key = ord(sys.argv[1][keyIndex % keylength].lower()) - 97 keyIndex += 1 translated.append(caesar(symbol, key)) else: translated.append(symbol) print("".join(translated)) exit(0)
from cs50 import get_string from math import floor AE1 = "34" AE2 = "37" MC1 = "51" MC2 = "52" MC3 = "53" MC4 = "54" MC5 = "55" Visa = "4" brand = "INVALID" # get and clean the input from the user card = get_string("Card n*: ") card = card.strip() count = len(card) # compare first 2 digits to the saved codes and assign a brand if (count == 13): if (card[:1] == Visa): brand = "VISA" elif (count == 15): if (card[:2] == AE1 or card[:2] == AE2): brand = "AMEX" elif (count == 16): if (card[:2] == MC1 or card[:2] == MC2 or card[:2] == MC3 or card[:2] == MC4 or card[:2] == MC5): brand = "MASTERCARD"
import cs50 import re # import of regular expressions words = cs50.get_string("Text: ") # read text into words string Lc_pattern = re.compile(r'[a-zA-Z]') # define pattern to search for letters Lc_matches = Lc_pattern.finditer(words) # find matches Lc = 0.0 for match in Lc_matches: # count matches Lc += 1 Wc_pattern = re.compile(r"[ ]") # define pattern to search for words Wc_matches = Wc_pattern.finditer(words) Wc = 1.0 # last word doesn't have a space after for match in Wc_matches: Wc += 1 Sc_pattern = re.compile(r'[.!?]') # define pattern to search for sentences Sc_matches = Sc_pattern.finditer(words) Sc = 0.0 for match in Sc_matches: Sc += 1 I = 0.0588 * ((Lc * 100) / (Wc)) - 0.296 * ((Sc * 100) / (Wc)) - 15.8 # Coleman-Liau index # print results if I < 1: print("Before Grade 1") elif I > 16: print("Grade 16+")
from cs50 import get_string from sys import argv def alpha(cc): if cc.islower(): return ord(cc) - 97 elif cc.isupper(): return ord(cc) - 65 k = int(argv[1]) pt = get_string("enter plaintext: ") ct = '' for c in pt: if c.isupper(): ct += chr((alpha(c) + k) % 26 + 65) elif c.islower(): ct += chr((alpha(c) + k) % 26 + 97) else: ct += c print(f'ciphertext: {ct}')
import cs50 import sys if len(sys.argv) != 2: print("Error: no argument or too many arguments given.") quit() elif str.isdigit(sys.argv[1]) == False: print("Error: You need to give positive integer") quit() key = int(sys.argv[1]) if key < 1: print("Error: wrong key") quit() text = cs50.get_string() if text != None: for w in text: if str.isalpha(w) == True: if str.isupper(w) == True: k = (ord(w) - ord('A') + key) % 26 + ord('A') print(chr(k), end="") elif str.islower(w) == True: k = (ord(w) - ord('a') + key) % 26 + ord('a') print(chr(k), end="") else: print(w, end="") print()
# test_wrd_cnt = cnt_words('I love cats@!') # print(test_wrd_cnt) # Create a function to get sentance count def sent_cnt(text): sents = list(map(str.strip, re.split(r'[.!?](?!$)', text))) return len(sents) # # Test my function for functionality # test_sent_cnt = sent_cnt('I love cats@! Dogs are great too.') # print(test_sent_cnt) # Prompt user to enter some text text = get_string('Text: ') ltrs = cnt_ltrs(text) # get letter count wrds = cnt_words(text) # get word count sents = sent_cnt(text) # get sentance count # Get L and S for Coleman-Liau Index formula L = ltrs / wrds * 100 S = (sents + 1) / wrds * 100 # Apply the Coleman-Liau Index formula index = (0.0588 * L) - (0.296 * S) - 15.8 # Get the grade level rounded grade = round(index)
from cs50 import get_string name = get_string("What is your name? ") print(f"hello, {name}")
import cs50 st = cs50.get_string("Text: ") l = 0 w = 1 s = 0 for i in range(len(st)): if (st[i].isalnum()): l += 1 if (st[i].isspace()): w += 1 if (st[i] == '.' or st[i] == '!' or st[i] == '?'): s += 1 L = 100 * l / w S = 100 * s / w index = 0.0588 * L - 0.296 * S - 15.8 if (index > 16): print("Grade 16+") elif (index < 1): print("Before Grade 1") else: print("Grade " + str((round(index))))
from cs50 import get_int from cs50 import get_float from cs50 import get_string # The Coleman-Liau index assesses the readability grade level in the US of a text passage using the below algorithm. # L is the average number of letters per 100 words in the text # S is the average number of sentences per 100 words in the text # index = 0.0588 * L - 0.296 * S - 15.8 text = get_string("Text: ") words = 1 letters = 0 sentences = 0 for i in text: if str.isalpha(i): letters += 1 for i in text: if i == " ": words += 1 for i in text: if i in (".", "!", "?"): sentences += 1 # print(letters) # print(words) # print(sentences)
# No printf # No semicolon at the end # No new line \n # No stdio.h header # No need to initialize the data type in the beginning print("hello, world") print("HELLO, WORLD") # Compile by using command line python program.py from cs50 import get_string answer = get_string("What's your name?\n") print("My name is " + answer) print("Toi ten la", answer) print(f"hello, {answer}") # counter++ does not exist counter = 0 counter += 1 # There's a colon # No brackers # No curly braces # Must be indented (convention is 4 spaces) # Else if turns into elif from cs50 import get_int x = get_int("x: ")
from cs50 import get_string import math import string while True: card_number = get_string("Enter your card number: ") if card_number.isnumeric(): break cardnum = list(map(int, card_number)) sum = 0 length = len(cardnum) parity = length % 2 for i in range(length): digit = cardnum[i] if i % 2 == parity: digit *= 2 if digit > 9: digit -= 9 sum += digit if length < 13 or length > 16: print("INVALID") exit(0) elif sum % 10 != 0: print("INVALID") exit(0) elif cardnum[0] == 5 and cardnum[1] <= 5 and length == 16: print("MASTERCARD")
from cs50 import get_string from student import Student # Space for students students = [] # Prompt for students' names and dorms for i in range(3): name = get_string("name: ") dorm = get_string("dorm: ") students.append(Student(name, dorm)) # Print students' names and dorms for student in students: print(f"{student.name} is in {student.dorm}.")
import cs50 # promt user for input text = cs50.get_string("enter text: ") # initialize the counter varuables letter = 0 # word will be one cause there is no space befor the sentence word = 1 sentence = 0 # itarate throught the sentence and add a one to letter each time we land on a ltter for i in range(len(text)): if text[i].isalnum() == True: letter += 1 # add to word each time we land on a space elif text[i] == " ": word += 1 # add to sentence each time we land on a punctuation elif text[i] == (".") or text[i] == ("!") or text[i] == ("?"): sentence += 1 # use a formula to colculate the grade level based on the amount of words letters and sentences l = float(letter) / float(word) * 100 s = float(sentence) / float(word) * 100 index = 0.0588 * l - 0.296 * s - 15.8 grade = round(index) # print the appropriate grade level if grade > 16: print("Grade 16+")
def get_plain(prompt): return get_string(prompt)
from cs50 import get_string s = get_string("What's your name?:\n") print(f"hello, {s}")
from cs50 import get_string s = get_string("Input: ") print("Output: ", end="") # Original for i in range(len(s)): print(s[i], end="") print() # Progress1 for c in s: print(c, end="") print()
from cs50 import get_string s = get_string("Enter: ") # In python char data type doesn't exist if s == "y" or s == "Y": print("Agreed.") # We can use single cote or double cote elif s == 'n' or s == 'N': print("Not agreed.") # y or any and permutation of yes (Yes, YES) is allowed if s.lower() in ["y", "yes"]: print("Agreed!") elif s.lower() in ["n", "no"]: print("Not agreed!")
def main(): answer = get_string("What is your name? ") print(f"Hello, {answer}.")
from cs50 import get_string name = get_string("Enter your name: ") print("Hello,", name)
# Check if there is only one command-line argument if len(sys.argv) != 2: print("Usage: python vigenere.py k") sys.exit(1) # Check if the single command-line argument: a keyword, k, is composed entirely of alphabetical characters if not (sys.argv[1]).isalpha(): print("Usage: python vigenere.py k") sys.exit(1) # Get cipher key key = sys.argv[1] # Get plaintext from the user plaintext = cs50.get_string("plaintext: ") # Cipher plaintext: ciphertext = "" # Point to 0th (first) key character j = 0 # Iterate over plaintext characters: for i in range(len(plaintext)): # get i-th plaintext character cp = plaintext[i] # if is alphabetical: if cp.isalpha():
# Jason Berinsky # CS 50 Problem Set 6 # Implements a Vigenere cipher in Python from cs50 import get_string import sys from sys import argv if len(sys.argv) != 2: sys.exit("Usage: python vigenere.py keyword") key = argv[1] if key.isalpha() == False: sys.exit("Usage: python vigenere.py keyword") plaintext = get_string("plaintext: ") cipher = list(plaintext) textlength = len(plaintext) keylength = len(key) j = 0 for i in range(textlength): if ord(key[j]) >= ord('a'): letter = chr(ord(key[j]) - ord('a')) else: letter = chr(ord(key[j]) - ord('A')) if ord(plaintext[i]) >= ord('A') and ord(plaintext[i]) <= ord('Z'): cipher[i] = chr(ord('A') + ((ord(plaintext[i]) - ord('A')) + ord(letter)) % 26) j = j + 1 elif ord(plaintext[i]) >= ord('a') and ord(plaintext[i]) <= ord('z'): cipher[i] = chr(ord('a') + ((ord(plaintext[i]) - ord('a')) + ord(letter)) % 26) j = j + 1 if j == keylength: j = 0
else: #Get number of stocks to put in portfolio and to promt user for x amount of tickers. Also validate that x>=2 while True: try: n_stocks = cs50.get_int("Input number of stocks: ") assert (n_stocks > 1) break except: print("Number of stocks must be greater than or equal to 2") while n_stocks > len(selected): stock = input("Enter stock ticker: ") selected.append(stock) #promt for time interval. If no end date, todays date is used date_start = cs50.get_string("Input starting date (YYYY-MM-DD): ") date_end = cs50.get_string("Input ending date (YYYY-MM-DD): ") if not date_end or date_end > datetime.today().strftime('%Y-%m-%d'): date_end = datetime.today().strftime('%Y-%m-%d') data = quandl.get_table('WIKI/PRICES', ticker=selected, qopts={'columns': ['date', 'ticker', 'adj_close']}, date={ 'gte': date_start, 'lte': date_end }, paginate=True) # reorganise data pulled by setting date as index with columns of tickers and their corresponding adjusted prices clean = data.set_index('date')
def prompt(): plaintext = get_string('plaintext: ') return plaintext
# Compares two strings for equality while checking (succinctly) for errors import sys from cs50 import get_string # Get a string s = get_string("s: ") if not s: sys.exit(1) # Get another string t = get_string("t: ") if not t: sys.exit(1) # Compare strings for equality if s == t: print("same") else: print("different")
def Promt(): message = get_string('What message would you like to censor?\n') messagelist = (message.lower()).split() return message, messagelist
import cs50 from estudiante import Student students = [] for i in range(3): print("name: ", end = "") name = cs50.get_string() print("dorm: ", end = "") dorm = cs50.get_string() students.append(Student(name, dorm)) for student in students: print("{} is in {}.".format(student.name, student.dorm))
import cs50 print("s: ", end = "") s = cs50.get_string() print("t: ", end = "") t = cs50.get_string() if s != None and t != None: if s == t: print("same") else: print("not same")
import sys from cs50 import get_string key = int(sys.argv[1]) text = get_string("plaintext: ") for i in range(len(text)): if(text[i].isalpha()): if(text[i].islower()): text = text[:i] + chr(((ord(text[i]) - ord('a') + key) % 26) + ord('a')) + text[i + 1:] else: text = text[:i] + chr(((ord(text[i]) - ord('A') + key) % 26) + ord('A')) + text[i + 1:] print("ciphertext: {0}".format(text))
from cs50 import get_string s = get_string("Name: ") if s.isupper() != True: print(s.upper()) else: print(s)
from cs50 import get_string s = get_string("What is your name?\n") print("hello,", s)
from cs50 import get_string # print("Before: ", end = "") s = get_string("Before: ") t = s.upper() print(f"After: {t}") # Another approach for c in s: print(c.upper(), end="") print()
# get_string and print from cs50 import get_string s = get_string("name: ") print(f"hello, {s}")
import cs50 s = cs50.get_string() if s != None: for c in s: print(c)
from cs50 import get_string a = get_string("Number: ") if (len(a) < 13 or len(a) == 14 or len(a) > 16): print("INVALID\n") else: str1 = "" for i in a: str1 = i + str1 sum = 0 for i in range(1, len(str1), 2): temp = int(str1[i]) temp = temp * 2 temp1 = str(temp) for j in temp1: temp2 = int(j) sum += temp2 for i in range(0, len(str1), 2): temp = int(str1[i]) sum += temp s = str(sum) if (s[len(s) - 1] == '0'): if (len(a) == 15 and a[0] == '3' and (a[1] == '4' or a[1] == '7')): print("AMEX\n") elif ((len(a) == 13 or len(a) == 16) and (a[0] == '4')): print("VISA\n") elif (len(a) == 16 and a[0] == '5' and a[1] in ['1', '2', '3', '4', '5']): print("MASTERCARD\n")