Day 12: Prime Number

 

# Ask the user for a number and determine whether the number is prime or not.

# import os

def enternum():
    test = int(input("Enter a number: "))
    checkprime(test)


def checkprime(test):

    if test == 1:
        print("The number is neither prime or composite.!")
    elif test == 2:
        print("The only even number which is prime!")
    elif test > 2:
        ghetto = int(test / 2)
        for i in range(2, ghetto + 1):
            if test % i == 0:
                i += 1
                print("Not a prime number!")
                break
            else:
                print("Prime number!")
                break

    flag = input("Want to try again? Y/N : ").lower()
    if flag == 'y':
        # os.system('cls')
        enternum()
    else:
        exit()


def mainstart():
    check = int(input("Enter 1 to check the number is prime or not. Press 2 to quit ::: "))
    if check == 1:
        enternum()
    elif check == 2:
        quit()
    else:
        print("Invalid Input. Try again.")

mainstart()

 

Advertisements

Day 11: And it continues with a list question again!

# Generate two random lists for different lengths
# and write a program that returns a list that contains only the elements
# that are common between the lists (without duplicates).
# Make sure your program works on two lists of different sizes.

import random

test1 = int(input("Enter the length of the first array: "))
test2 = int(input("Enter the length of the second array: "))

a = [random.randint(0, 100) for i in range(test1)]
b = [random.randint(0, 100) for i in range(test2)]
print(a, b)
c = print([i for i in a if i in b])

Lessons learned:

  1. Getting random numbers in your list makes it tough to find a common element in both the list with such a large data pool.
  2. You can literally shove the entire condition in one single line of code to find unique elements from both the lists.
  3. You cannot append the list at the end of the condition. Here, it meant printing the values in c. I was doing ==> c = print[for i in a if i in b c.append/c] <== which is not the correct method. Apparently it shows invalid syntax with expression required. Need to figure this out.

Day 11: Fibonacci Series

After 100 million times trying to figure out how to write the series in simplest way without recursion, I finally got it. I have no idea why, but it took me time. =/ But Yeay! It worked! 🙂

# Print Fibonacci Series

a = 0
b = 1
test = int(input("Enter the range till you want the series: "))

print(a)
print(b)

for i in range(test):
    c = a+b
    print(c)
    a = b
    b = c

Day 11: Guessing Game

# Generate a random number between 1 and 9 (including 1 and 9).
# Ask the user to guess the number,
# then tell them whether they guessed too low, too high, or exactly right.
# Also count the number of attempts the user made.

import random

num = random.randint(1, 10)
flag = 0


def guessnum(num, player, flag):
    if player == num:
        print("Same")
        flag += 1
        print("You took " + str(flag) + " chances.")
    elif player < num:
        print("You have entered a low value.. Try again!")
        bleh = int(input("Enter a new Number: "))
        flag += 1
        guessnum(num, bleh, flag)
    elif player > num:
        print("You have entered a higher value.. Try again!")
        bleh = int(input("Enter a new Number: "))
        flag += 1
        guessnum(num, bleh, flag)

test = int(input("Do you want to play a game? 1 to enter, 2 to exit: "))

if test == 1:
    player = int(input("Guess the number: "))
    guessnum(num, player, flag)
elif test == 2:
    print("Okay Bye")
    exit()

Lessons Learned:

  1. Looping can get dangerous. Use it properly.
  2. Passing different attributes to functions depending on the code.

Day 10: Rock Paper Scissors

So my next challenge was to create a game of Rock Paper Scissors. We were suppose to take inputs from user and create the game with some predefined rules.

Ignore the short terms. And a little nittie gritties here and there.

# Make a two-player Rock-Paper-Scissors game.
# Remember the rules:
# Rock beats scissors
# Scissors beats paper
# Paper beats rock

import random


def multiplayer():
    p1 = input("Player 1 R/P/S: ").upper()
    p2 = input("Player 2 R/P/S: ").upper()

    if p1 == p2:
        playagain = input("Draw.. Want to play again? Y/N: ").upper()
        if playagain == 'Y':
            Main()
    elif p1 == 'R' and p2 == 'S':
        print("Player 1 wins..")
    elif p1 == 'S' and p2 == 'P':
        print("Player 1 wins..")
    elif p1 == 'P' and p2 == 'R':
        print("Player 1 wins..")
    elif p2 == 'R' and p1 == 'S':
        print("Player 2 wins..")
    elif p2 == 'S' and p1 == 'P':
        print("Player 2 wins..")
    elif p2 == 'P' and p1 == 'R':
        print("Player 2 wins..")
    response = input("Want to play again? Y/N: ").upper()
    if response == 'Y':
        Main()
    else:
        quit()


def computer():
    option = ['r', 'p', 's']
    while True:
        cpu_choice = random.choice(option)
        human = input("Player 1 R/P/S: ").lower()
        print(cpu_choice)
        if cpu_choice == human:
            playagain = input("Draw.. Want to play again? Y/N: ").upper()
            if playagain == 'Y':
                Main()
        elif cpu_choice == 'r' and human == 's':
            print("cpu_choice wins..")
        elif cpu_choice == 's' and human == 'p':
            print("cpu_choice wins..")
        elif cpu_choice == 'p' and human == 'r':
            print("cpu_choice wins..")
        elif human == 'r' and cpu_choice == 's':
            print("human wins..")
        elif human == 's' and cpu_choice == 'p':
            print("human wins..")
        elif human == 'p' and cpu_choice == 'r':
            print("human wins..")
        response = input("Want to play again? Y/N: ").upper()
        if response == 'Y':
            Main()
        else:
            quit()


class Main:
    def __init__(self):
        print("Welcome to RPS. Want to play Multiplayer (1)/ Computer (2)?")
        test = input("Press 1/2 to start: ")
        if test == '1':
            multiplayer()
        elif test == '2':
            computer()
        else:
            print("Invalid data.. Please try again..")
            Main()


Main()

 

Lessons Learned:

  1. Learned how to use classes to some extent. I’m still damn sure, I haven’t used it properly.
  2. Calling multiple functions from another function.
  3. Calling of self from the same function.

Lessons need to figure out:

  1. Why my break won’t work when I insert it in between.
  2. WHY? WHY? WHY!
  3. How to improve it now.

Day 9: Lambdas

Lambdas are functions which are used without any predefined variables and evaluate to single line of code.

# a list saved in a variable: a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100].
# Write one line of Python that takes this list a
# and makes a new list that has only the even elements of this list in it.

a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
b = list(filter(lambda x: x % 2 == 0, a))

print(b)

Lessons Learned:

  1. I think I’m finally getting  hang of it. It = “Python”
  2. List was used because we had to make a new list as per the challenge.
  3. Filter is used when we have to show an element in the sequence for which the function results true.
  4. Lambdas was used to evaluate the expression in single line.
  5. Lambda functions are mainly used in combination with the functions filter(), map() and reduce().
  6. We can do single line of code if it is not going to be used again.

To have more knowledge about the above mentioned, please refer to this link:

http://www.python-course.eu/python3_lambda.php

Also it looks a great site if you are starting up.

 

Day 8: Palindrome

I was kind of waiting for this exercise to come. I mean this and fibonacci is one of the most awaited noob level exercises faced in early stages of development.

Anyway, so the challenge was to accept a string and check whether that is a palindrome or not.

# Ask the user for a string and print out whether this string is a palindrome or not.

raw = str(input("Enter a string: "))
raw.replace(" ", "")
set1 = str.lower(raw[::-1])
set2 = str.lower(raw[0::])
if set2 == set1:
    print("Palindrome")
else:
    print("Not a palindrome")

Lessons learned:

  1. First start off using a simple word to check for palindromes. (Imagine what you have to do and try putting that in code)
  2. Practice slicing of strings and arrays/lists.
  3. Easier way of string comparison is to take the string and store it in reverse in a new variable and one to store the original value and then compare both.
  4. Additional features –>
    • String can be camel case as well. So ensure that the both the strings stored is in same format.
    • Remove/Trim any extra spaces.
  5. Work your way around a stream of words using 4(b) method. I found that easy.

Day 7: Creating random lists and finding common numbers in them

The task for this was to create two random list of variable lengths and finding common numbers between them.

# Take two random lists
# and write a program that returns a list that contains only the elements
# that are common between the lists (without duplicates).
# Make sure your program works on two lists of different sizes.

import random

a = random.sample(range(100), 10)
b = random.sample(range(100), 15)
c = []

print(a)
print(b)
for num in a:
    if num in b:
        c.append(num)

print(c)

 

Lessons Learned:

#1: Instead of using randit from random library, we can use sample which is made to generate a list of random numbers.

#2: When you use sample, you don’t need to define variables as a list. (like a = list[random……]

#3: Totally ignored the last line where range() object had to be passed as an object. I was passing values directly to sample which kept on throwing me error.

random.sample(population, k)

Return a k length list of unique elements chosen from the population sequence or set. 
Used for random sampling without replacement.

Returns a new list containing elements from the population while leaving the original population unchanged. 
The resulting list is in selection order so that all sub-slices will also be valid random samples. 
This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices).

Members of the population need not be hashable or unique. 
If the population contains repeats, then each occurrence is a possible selection in the sample.

To choose a sample from a range of integers, use an range() object as an argument. 
This is especially fast and space efficient for sampling from a large population: sample(range(10000000), 60).

#4: Forgot I could easily use in function to find common elements.

 

Day 6: Create a program that asks the user for a number and then prints out a list of all the divisors of that number.

# Create a program that asks the user for a number
# and then prints out a list of all the divisors of that number.

num = int(input("Enter a number"))
check = list(range(1, num+5))

for number in check:
    if num % number == 0:
        print(number)

 

num – takes the input of the user for the number.

check – is a list which contains all the elements for the range defined.

Then we have a loop which starts with the element in check list checking out all the possible values in the list. *haha.. did you get the pun?!*

Then we have an if loop which checks whether the number inputted by the user is divisible completely by any of the number in the range which is defined in check.

Finally we print out all the values of the number which are divisible completely. It took me a while to figure what to print out.

FYI: Range can be defined anything by you. Doesn’t necessarily have to be +5.

PPPS: I wrote all my PS’s before the explanation of the code.

PS: Phew! No one holla-ed me but I still gave it anyway. I know I suck at explanations. I’ll definitely improve myself.

PPS: I personally find myself hilarious which is huge misconception and is generally agreed by everyone in my circle. You can definitely ignore all the puns in-spite of the fact that I know you would be laughing and saying things like ‘oh-so-genius with her jokes’. Just saying. #ignore

Day 5: Still stuck on Lists

I didn’t study last night. *sloth sloth sloth <echos>* I agree my bad. And I should keep moving forward without boring WordPress out with lists though. * sloth sloth sloth <keeps echoing in the background>*

So this is the last list problem which I’ll post. Practice list but post other things.  But this question made me question myself.

# Write a Python program to get a list,
# sorted in increasing order by the last element
# in each tuple from a given list of non-empty tuples.
# Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
# Expected Result : [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]

from operator import itemgetter

def last(n):
    return n[-1]

def first(n):
    return n[0]

def sort (a):
    return sorted(a, key=last)

def sort_dec(a):
    return sorted(a, key=itemgetter(1), reverse=True)
a = [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
print(sort(a))
print(sort_dec(a))

I learned about operator library, sorting, itemgetter. I’ll learn more.

Holla if you want me to set down explanations as well. Don’t holla. Just comment. *Thought to self: What am I?*