Create a Python dictionary that returns a list of values for each key. The key can be whatever type you want.
Design the dictionary so that it could be useful for something meaningful to you. Create at least three different items in it. Invent the dictionary yourself. Do not copy the design or items from some other source.
def invert_dict(d):
inverse = dict()
for key in d:
val = d[key]
if val not in inverse:
inverse[val] = [key]
else:
inverse[val].append(key)
return inverse
Modify this function so that it can invert your dictionary. In particular, the function will need to turn each of the list items into separate keys in the inverted dictionary.
Run your modified invert_dict function on your dictionary. Print the original dictionary and the inverted one.
Include your Python program and the output in your Learning Journal submission.
Describe what is useful about your dictionary. Then describe whether the inverted dictionary is useful or meaningful, and why.
alphabet = "abcdefghijklmnopqrstuvwxyz"
test_dups = ["zzz","dog","bookkeeper","subdermatoglyphic","subdermatoglyphics"]
test_miss = ["zzz","subdermatoglyphic","the quick brown fox jumps over the lazy dog"]
def histogram(s):
d = dict()
for c in s:
if c not in d:
d[c] = 1
else:
d[c] += 1
return d
Part 1
Write a function called has_duplicates that takes a string parameter and returns True if the string has any repeated characters. Otherwise, it should return False.
aaa has duplicates
abc has no duplicates
Part 2
Write a loop over the strings in list test_miss and call missing_letters with each string. Print a line for each string listing the missing letters. For example, for the string "aaa", the output should be the following.
aaa is missing letters bcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz uses all these letters
Describe how tuples can be useful with loops over lists and dictionaries, and give Python code examples. Create your own code examples. Do not copy them from the textbook or any other source.
Your descriptions and examples should include the following: the zip function, the enumerate function, and the items method.
Anti-Diagonals
Given a MxN matrix,write a program to print all Anti-Diagonals elements of matrix
Input
The first line of input will contain a M, N values separated by space.
The second line will contain matrix A of dimensions MxN.
Output
The output should contain anti-diagonal elements separated by a line.
Explanation
Abhinav and Anjali are playing Rock-Paper-Scissors game. Rock-Paper-Scissors is a hand game usually played between two people, in which each player simultaneously forms one of three shapes with an outstretched hand. These shapes are "rock", "paper" and "scissors". Based on the shapes the player chooses the outcome of the game is determined. A rock beats scissors, scissors beat paper by cutting it, and paper beats rock by covering it. If the same shape is chosen by both of the players, then it is tie. Write a program to decide the winner of each round of the game based on the shapes the players chose.Input
The first line of input will be one of the strings "Rock", "Paper", "Scissors", representing the shape chosen by Abhinav.
The output should either be "Abhinav Wins" or "Anjali Wins", based on the winner. If it is a tie, the output should be "Tie".
Given the number of rows N, write a program to print the hallow diamond pattern similar to the pattern shown below.
A
B B
C C
D D
E E
D D
C C
B B
AThe input will be a single line containing a positive integer (N).Output
The output should be (2*N - 1) rows and (2*N - 1) columns containing the alphabet characters in the hollow diamond pattern.Explanation
For example, if the given number is 5, the pattern should contain 9 rows and 9 columns as shown below.
A
B B
C C
D D
E E
D D
C C
B B
AAnti-Diagonals
Given a MxN matrix,write a program to print all Anti-Diagonals elements of matrix
Input
The first line of input will contain a M, N values separated by space.
The second line will contain matrix A of dimensions MxN.
Output
The output should contain anti-diagonal elements separated by a line.
Explanation
For example, if M = 4, N = 4
Matrix A:
4 4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
So the output should be
1
2 5
3 6 9
4 7 10 13
8 11 14
12 15
16
Sample Input 1
2 3
1 5 5
2 7 8
Sample Output 1
1
5 2
5 7
8
Sample Input 2
3 4
1 2 3 4
5 6 7 8
9 10 11 12
Sample Output 2
1
2 5
3 6 9
4 7 10
8 11
12Numbers in String - 2
Given a string, write a program to return the sum and average of the numbers that appear in the string, ignoring all other characters.Input
The input will be a single line containing a string.Output
The output should contain the sum and average of the numbers that appear in the string.
Note: Round the average value to two decimal places.Explanation
For example, if the given string is "I am 25 years and 10 months old", the numbers are 25, 10. Your code should print the sum of the numbers(35) and the average of the numbers(17.5) in the new line.
You are given a square matrix A of dimensions NxN. You need to apply the below given 3 operations on the matrix A.
Rotation: It is represented as R S where S is an integer in {90, 180, 270, 360, 450, ...} which denotes the number of degrees to rotate. You need to rotate the matrix A by angle S in the clockwise direction. The angle of rotation(S) will always be in multiples of 90 degrees.
Update: It is represented as U X Y Z. In initial matrix A (as given in input), you need to update the element at row index X and column index Y with value Z.
After the update, all the previous rotation operations have to be applied to the updated initial matrix.
Querying: It is represented as Q K L. You need to print the value at row index K and column index L of the matrix A.
Sample Input 1:
The first line contains a single integer N.
Next N lines contain N space-separated integers Aij (i - index of the row, j - index of the column).
Next lines contain various operations on the array. Each operation on each line (Beginning either with R, U or Q).
-1 will represent the end of input.Output
For each Query operation print the element present at row index K and colum index L of the matrix in its current state.Explanation
For Input:
2
1 2
3 4
R 90
Q 0 0
Q 0 1
R 90
Q 0 0
U 0 0 6
Q 1 1
-1
Initial Matrix
1 2
3 4
For R 90, clockwise rotation by 90 degrees, the matrix will become
3 1
4 2
For Q 0 0, print the element at row index 0 and column index 0 of A, which is 3.
For Q 0 1, print the element at row index 0 and column index 1 of A, which is 1.
Again for R 90, clockwise rotation by 90 degrees, the matrix will become
4 3
2 1
For Q 0 0, print the element at row index 0 and column index 0 of A, which is 4.
For U 0 0 6, update the value at row index 0 and column index 1 in the initial matrix to 6. So the updated matrix will be,
6 2
3 4
After updating, we need to rotate the matrix by sum of all rotation angles applied till now(i.e. R 90 and R 90 => 90 + 90 => 180 degrees in clockwise direction).
After rotation the matrix will now become
4 3
2 6
Next for Q 1 1, print the element at row index 1 and column index 1 of A, which is 6.
output
3
1
4
6
sample input:2
2
5 6
7 8
R 90
Q 0 1
R 270
Q 1 1
R 180
U 0 0 4
Q 0 0
-1
sample ouput 2:
5
8
8
Code that i wrote is:
n=int(input())
matrix=[]
for i in range(n):
a=input().split()
matrix+=[a]
def transpose_matrix(matrix):
for i in range(len(matrix)):
for j in range(i,len(matrix)):
matrix[i][j], matrix[j][i] = matrix[j][i],matrix[i][j]
def reverse_rows(matrix):
for i in range (len(matrix)):
k = len(matrix) - 1;
for j in range(0,k):
matrix[i][j], matrix[i][k] = matrix[i][k], matrix[i][j]
k = k - 1
def rotation(angle):
number=int(angle)/90
number=int(number)
for i in range(number):
transpose_matrix(matrix)
reverse_rows(matrix)
angle=0
while True:
para=input()
if para=="-1":
break
else:
parameter=para.split()
if parameter[0]=="R":
rotation(int(parameter[1]))
angle+=int(parameter[1])
elif parameter[0]=="Q":
a=int(parameter[1])
b=int(parameter[2])
print(matrix[a][b])
elif parameter[0]=="U":
a=int(parameter[1])
b=int(parameter[2])
c=int(parameter[3])
matrix[a][b] = c
rotation(angle)
but im not getting the desired output for second input.... can anybody share the working code for this.
Explore the dependence of the period of a pendulum's motion as a function of its initial amplitude. Complete tasks inside the TODO #
import numpy as np
from scipy import interpolate
from scipy import integrate
import matplotlib.pyplot as plt
class pendulum:
''' defines a simple pendulum '''
def __init__(self, pendulum_length, mass):
# TODO: Assignment Task 1: write method body
# End of Task 1; proceed to task 2.
def set_g(self, g):
''' small g to be used in calculations '''
self._g = g
def dydt(self, y, t):
""" Calculate the derivatives for a pendulum
Parameters
----------
y: array-like
vector of unknowns for the ode equation at time t
t: float
time t
Returns
-------
ret: numpy array of float
the derivatives of y
"""
# TODO: Assignment Task 2: write method body
# End of Task 2; proceed to task 3.
def period(self, maximum_amplitude):
''' Calculate the period of the periodic motion.
For amplitude=0 the small amplitude analytical solution is returned.
Otherwise the period is calculated by integrating the ODE using
scipy.integrate.odeint() and determining the time between release at
maximum amplitude and the first angle=0 crossing. The exact zero
crossing is determined using scipy.interpolate.interp1d().
In the calculation it is assumed that the period has a value between
90% and 150% of the small amplitude period.
Parameters
----------
maximum_amplitude: float
maximum amplitude of the periodic motion
Returns
-------
p: float
the period
'''
# TODO: Assignment Task 3: write method body
# End of Task 3; no further tasks.
if __name__ == '__main__':
#some test code
pen = pendulum(1, 1)
pen.set_g(9.81)
#generate data for figure
angles = np.linspace(0, np.pi/2, 31)
period_ode = [pen.period(a) for a in angles]
# generate a plot
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(angles, period_ode, 'b', label='generated using ode')
ax.set_title('Period of a 1m Pendulum as a Function of Amplitude')
ax.set_xlabel('amplitude/rad')
ax.set_ylabel('period/s')
ax.legend(loc='upper left')
plt.show()