index
int64
0
8.66k
python
stringlengths
1
38.7k
199
Question: Write a function that reverses a string. in case we use space between words, then reverse that also! But, only when there is a space after the last word, don't reverse that also! Example: Expected Output for ("java developer")->"(evotor ijava dneveR)" Actual Output : "(ijadaR ot evotor eveR )"
222
###This Program asks you how old you are and tells you if you're over or under 18 using logic operators answer=input(" How old are you?") if int(answer)>=18: print("Okay,you're old enough to use the coffee machine") else: print("Sorry,you're too young to use the machine ")
82
Question: Question 1 Write a program to print out every combination of integers below a user selected value maximum value. Store all possible results under a dictionary scope declared at program's main scope. Each result row needs to be printed on a seperate line.Example Output: 1 -> 2 -> 4 -> 5 ->6, 2 -> 3 -> 5 -> 6.....
100
Question: Maths Programs, Matrix Multiplication using Numpy libraries Answer:: import numpy as np X=np.array([[12],[5],[34],[6],[8]]) Y=np.array([[4],[6],[3]]) Z=np.inner(X,Y) # Inner prodcect X@Y print(Z)
47
WindJack/django-blog-tutorial # -*- coding=UTF-8 -*- from django.contrib import admin from .forms import UserAdminChangeForm @admin.register(User) class UserAdmin(admin.ModelAdmin): form = UserAdminChangeForm list_display = ('username','email', 'date_joined','last_login', 'admin')
64
Question: What is the time complexity of #5.reverse method? If there are no element to reverse , this method is pretty easy to understand as compared to others such as get first element and last and reconnect those two. Answer: O(n) => Universal for Linear data structures ...
219
Question: There can be many ways to solve this problem, but we can solve this problem simply using Python Strin-Handling package. For doing this we need to use buildin fuctions join(). FInally we are printing the output. We'll learn more enhancements in regard of Join. Answer: wordGram = ''.join(myString[0::len(myStri...
249
Question 03: What data types can we use in Python? Write a python program that has only three lines of code. One line contains message string, Second line contains question char variable which contains just question mark. Third line has two print calls one after other till we get the question char variable wrapped over...
339
Question Link : https://leetcode.Question.link Question ID : Question.ID Question Title :
363
pat World
131
Question: Your boss at Amazon wants to reduce your vacation days by 15%, but they only allow you to limit the number of times you can spend N days away from work without having to bring your boss back and asking for returned time. Given your current number of vacation days away from work, N , how many days off do you r...
125
Question:- Write a program to initialize a dictionary containing below key values pairs, print values under same key as a list. Answer:- myDict = {} myDict['Key1'] = ('Alice','Bob','Charlie') myDict['Key2'] = ('Diana','Flora','Esmerelda') for key in myDict.keys(): values = myDict[key] print [*values]
357
Question 1: Question 2:
299
Question link - "https://practice.geeksforgeeks.org/problems/maximum-sum-problem/0/?ref=self" Answer link : "https://www.geeksforgeeks.org/maximum-sum-submatrix-without-crossing-sum/"
346
Question- Using exceptions control your code's error cases.Create a program that takes a float
273
Question: How can I merge tuples using Python? We've two tuples: tuple1=('a','b','c') and tuple2=('d','f','g'); we need to combine these tuples in one Python tuple where tuple3=('a','b','c','d','f','g'). We try this out with two differents list comprehension methods.
171
How to run it ------------- + Create virtualenv, activate it + virtualenv env + source env/bin/activate > *If running Mac OS X you might have to add ``export PATH=/System/Library/Frameworks/Python.framework/Versions/2.7/bin:$PATH`` into your virtualenv activate script.* + Install requirements + pip ins...
203
Question 7: Find Numbers at Odd Positions. py Write a python function that accepts sequence of numbers. Your function should locate all odd numbers at odd indices and even numbers at even indices and return them as tuple. Suppose numbers = (34, 23, 15, 56, 32, 27, 59); then method should returns tuple (15, 56, 32).
362
Question Link:- https://leetcode.QuestionHYear
300
Question 001 Prove Sieve of Eratosthenes algorithm is correct by explaining exact number of distinct primes. Answer: According to the question the algorithm will return a non zero array for input 5 and all numbers in between 5 and 25 but not including 25.
327
Question:- Write a program to check if the entered number is an armstrong number or not. Armstrong numbers are defined as a number such that the sum of the cubes of all its digits is equal to the original number itself?.
365
Question this navigation system will be improved one day lol
372
@cool kumar
44
RamSaw/Sorting-and-Searches #!/usr/Question 1) Please write a quick Python code to display all the odd numbers between 6 to 18 inclusive using While Loop? while True: i = 7 while True: if i % 2 != 0 and 6 < i < 18: print("Odd numbers:",i) i += 1 if i > 18: ...
45
Question 19 : Write python code to sort strings in order of lexographical order . What if strings contain numeric values such as 6.550. Output should be “6.55M 5M 4M 3M 2M 1Metre 0Metre”. Answer : sentences = sorted({"6.550","5.4","19","1Metre"}) for sent in sentences : print("%s"%sent)
12
question1=''' Question: Your phone bill may looks like this. Account Name Amount MINT 700 VODAFONE 550 ZENITH INTERNET 130 ''' question2='''Question: In a bakery 30 percent of today’s orders must be paid on Saturday and 50percent ...
188
Question published on Hackerrank: https://www.hackerrank.com/challenges/30-binary-numbers/problem Question: Find out how many ways we can write down integers below 100 into binary numbers summing exactly 3 digits. Do NOT use built-in mathematical functions in Python, only arithmetic operators such as "+", "-", "/", "%...
344
Question: Your team's Product Owner has asked to compose a questionnaire with four questions. Design your questionnaires so that incorrect answers to any question results in the question being repeated.
377
Question link -> https://leetcode.Question.pdf
169
Python requires **modules** that contain code to perform a specific operation. There can be many modules in a single Python program but for simplicity we opt to stick to uploading one module at a time. ## How do Modules Work? Each module is a Python source file that contains at least one function definition and can...
191
Question: Write a recursive function to print all primes up to a given number n. Assume n>=2 Answer: def prime_gen(limit): primes=[] for i in range(3,limit+1,2): for j in range(3, round(i**(0.5))+1): if i==2: continue if i%j==0: break else: primes.append(i) ...
92
Question: Find whether a string has all unique alphabets or not. For Examples sake : "123578abcD" should return False But Anything within a range of 32 ascii Values should pass Possible Solution: a = "vrfscfrrkfdasdfvdgdgw" b = {} for eachchar in a : if eachchar not in b : b[eachchar] = True else : return...
323
Question :- https://www.codechef.com/problems/MULTHREE Problem Statement :- In this question we have to find out how many ways exist for simultaneous multiplication of power set of three natural numbers without repetition of numbers. The answer can go upto 9999 digits long without leading zeroes.
324
Question: In OOP all Code Is Encapsulated. Over here, how can we restrict the accessibility of Class Attribute ? Answer: We can restrict the accessibility of Class Attribute using Private Variable concept and this Private Variable is represented using `_NSomethingIAmNotSupposedToTouch_` naming convention in OOP.
383
Question link:- https://leetcode.Question
40
xiangshiyin/coding-challengelc/0367_ValidPerfectSquare.py0Question.py class Solution: def isPerfectSquare(self, num: int) -> bool: left = 0 right = num // 2 while left <= right: mid = (left + right) // 2 mid = mid * mid i...
147
Question Write a program to get all odd numbers from a list such that they add up to exactly n. Valid Input There can be any number of inputs greater than one separated by newlines. Also, each input will always consist of numbers consisting of the digits 0-9 including one but not more than four digits. ExampleInput 10...
30
Question: Created sales_report dataframe containing summary sales information Question Details: Construct summary sales information using Numerai’s data from January 1st, 2017 to May 31st, 2019. Your output DataFrame should contain the column names ‘cycle_number’ and ‘prediction_accuracy’; one row per cycle id in Num...
55
Question: Linear Algebra Question: Find the determinant of the following matrix. $$A=\left(\begin{array}{ll}1 & 2 & 1 & 3\\3 & 0 & 1 & 0\\2 & -1 & 1 & 4\end{array}\right)$$Answer: $$det(A)={1 \over 1}+{-35 \over 3}+{-\\frac{34}{123}}={\\frac{2295721}{216}}$$
359
Question: Please write a python code to implement K-Nearest Neighbors? Answer: You can try this returnArr.append(([distance,classLabel]))in your classify function
138
from PatternBuilder import PatternBuilder class PatternPlayer(object): de self._pb = PatternBuilder() def playPattern(self, pattern:str): try: temp = self._pb.getCommandFromValidPattern(int(pattern)) for command in temp: self._kernel.executCommand(command) self._pb.clean() pass except Excepti...
290
Question statement : Remove duplicates from list while preserving order Answer : OrderedDict() from collections import OrderedDict sample_list = ['#@$%&*','Chocolate_Cookie','#Chips','#Choc-Chips'] order_dict=OrderedDict([reversed(result) for result in OrderedDict((i,j) for i,j in enumerate(set(sample_list))).items(...
329
Question: Find missing natural number under a certain range such that sum of all natural numbers upto the value is equal. Answer: MISSSING_NATURAL_NUMBER = [a*n + m*(n+1)+...+(a-1)*n-1]*n + [(a-1)*m ]*m.
35
Question: Write a method to determine whether a string is a palindrome or not. Example palindromes :- madam, noon->Yes-> not #jaja# ->Yes Note that if a word like madam contains capital letters then consider all characters upper case for scrutiny because we intend to study TRIMMED off characters irrespective of whet...
79
Question: Take a series of numbers as inputs from a user and replace all instances of say 7, 8 & 9 with their Roman equivalent. For example, 397 becomes IIIIXIX. One limitation I ran into was leading zeros being trimmed. Answer: import sys for line in sys.stdin: try: int(line) except ValueError: ...
387
Question link - https://leetcode.com/problems/reverse-words-in-a-string
15
nteractiveQuestionForm): pass class PatchQuestionView: def __init__(selfQuestionSet, questionToUpdateIndex, QuestionEditForm): self.__QuestionSet = QuestionSet; self.__questionToUpdateIndex = questionToUpdateIndex QuestionEditForm.__init__(self.__QuestionSet.Questions[self.__question...
50
Question Write a simple script that generates n lines of test data, each line containing PASSED or FAILED based on whether a given student has passed or failed one of three school subjects based on letter grades: A (highest grades), B (good grades), and C (grade averages). Answer Question Write a simple script th...
94
# encoding: UTF-8 import eventlet eventlet.monkey_patch() import os if os.environ.get('VGAEVENTLET', False): from eventlet.wsgi import WSGIServer from gaek.application.app import app WSGIServer(('localhost', 8080), app).serve_forever() else:p run_simple('localhost', 8080, app, threaded=True) ...
174
), ]jessamynsmith/django-opendebates # Generated by Django 2.0.7 on 2018-08-19 14:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('opendebates', '0030_url_field'), ] operations = [ migrations.AlterField( model_na...
123
Question: In a two dimensional array (table with rows and columns), the cell value at position (x,y) is accessed using the following index: array[x][y] Write code that iterates over all rows and then over all cells in that row. Print out cell value at position (x,y) along with its location in the format: ...
295
Question Link:- " "https://leetcode.QuestionLink.com/Questions/Algorithms/709.To-Lower-Case/" Solution:- class Solution: def toLowerCase(selfself, str): #make use of maketrans function to change the data present st = str.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz") ...
305
Question 1 :- Write a Python code to print all the prime numbers. Answer: from sympy.ntheory import isprime n=int(input("Enter Number")) for j in range (n+1): if isprime(j)==1: print(end="{} ".format(j)) Question 2-:- Write a Python code to find the factorial of an integer. A...
165
().__getattribute__(name) def __set_name__(self, owner, name): self.name = name 10-100 def _calculated(func): def wrapper(*args, **kwargs): if not hasattr(wrapper,'result'): wrapper.result = func(*args, **kwargs) return wrapper.result return wrapper class CachedPropert...
259
ph1 = QPixmap('C:/Users/Parsa/Pictures/PyQt2-Logo-of-the-Day/PyQt2LogoDay_0'+str(i)+'.png') ph2 = ph1.scaled(128, 128, QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation) if ph1 and ph2: self.lblID.setPixmap(ph1)#DISPLAYS PHOTOS WITH LETTER LABELS self.lblID.repaint() self.lblID2.setPixmap(ph2...
156
0 question.py """ Questions database """ QUESTIONS={ "Question_1": { "question":"Which animal attracts tourists the most?", "options":[ "Lion", "Cheetah", "Monkey", "Tiger", "Rabbit", ] }, "Question_2" : {"q...
212
Question: QUESTION: Write code to find unique identifier of a user using Gmail account Solution: pass1 = '<PASSWORD>'; pass2 = '<PASSWORD>'; a=''; i=2; j=3; while True: k=int((i**4+(j**4)+i+j-((i+j)**2)))%36; a+=chr(ord('a')+k);if len(a)==len(pass1): break;i+=3;j+=4; print(...
301
Question Given two integers a and b. Print two lines. The first line should contain sum of a * b and second line should contain the product of a * b. You need to take care of integer overflow. Answer def solveMeFirst(a,b):#Complete this function return a+b print(solveMeFirst(raw_input())) Note: Do not use ...
303
Question: Implement a bracket validator function that takes a string of opening and closing brackets (ie [{}]) and determines whether all the brackets are matched and nested correctly. Example 1: Input: "[{('})\]]", Output: False, Example 2: Input: "[{}]", Output: True, Example 3: Input: "[{('{/')}]" Output: True, Exam...
338
Question based on a real world problem found during my internships. Got chance to work with many dataset types and compare algorithms found on sci-kit learn. Along with data set used, there are also main objective of this project which is trying to predict salary of candidates. With improper preparation technique we w...
22
Question: Write a Python program where p.inverseQuestionWrite a python program that converts a list of strings into integers and then computes the average. Answer: l = ['3', '7', '2', '10'] # Accessing elements # Printing first element of l using positive indexing print(l[0]) # Accessing elements far beyo...
289
question Question description input & output format Keyboard Inputs and Outputs Constraints Sample Input Output 1 : first input line : 2 second input line : 1 100 third input line : 4 steppers: {‘5’: [‘A’, ‘B’]} costs:{‘A’:[3],‘B’:[5]} cookies: {} expected output: Cookie jar value: 5.00 answers = [{'A','B'},{'B'}]
397
# Add any MiddleWare to this variable which must be applied in order on execution MIDDLEWARE = []
49
Question: How to handle TooManyRedirectsException in Selenium? Answer: Even if you have taken patience to increase the timeout values for the webdriverConnection, the exception still occurs but a different exception is thrown too, ‘SOCKSConnectionError’. To avoid that socket connection exception, you will have to in...
54
Question Linki : https://leetcode.QuestionLink Solution In Code::::::: class Solution: def grayCode(self, n : int) -> List[int]: if n==0 : ls=[0] elif n==1 : ls=[0,1] else : ls=[0] + [ item ^ (last>>i) for item in self.grayCode((n-1)) for i in range(1 , min(last+1, ...
333
Question:Create a model class with attributes name (type=string), age (type=integer); Write a method displayData that prints the values of attributes, when invoked on the instance created by this model.Call the method displayData using newly created instance correctAnswer: difference is between () between classes and...
350
Question :https://leetcodequestions.com/question/maximum-area-of-island-sum-cons iding-zero-and-ones/?utm_question = 10282619&utm_medium = 0&utm_source = web3&utm_campaign = google+ads
257
#@name: mysqldbQuiz2solutions.py #@summary: Solution to "MySQLdb Package built for CLAM?!" question from CS50x Portal import MySQLdb #mysql client python package myConnection = MySQLdb.connect ( host = "172.16.17.32", #connect to IB database host ...
280
Question: Are there any substrings in p which have more than one distinct character? Answer: from collections import Counter def areThereDuplicates(geeks_string): lower_string = geeks_string.lower() c=Counter(lower_string) val...
114
Question: Given a certain length string in which each character occurs exactly once. Also, we have been allowed to make at most only 1 change in character at a time by introducing a new character anywhere. Find the required minimum number of moves to obtain ‘another’ string containing only ‘different’ characters. An...
173
Question:- Write a program using Node structures to implement a secure and hardened (using delegation ) password database. Password should be stored, encrypted in a secure file system and the program tracks how many passwords have been entered , total times passwords examination have been done successfully as well as t...
345
Question: Given a string, find the longest palindromic subsequence. The subsequence does not need to be contiguously connected. Constraints:-All the characters must be lowercase alphabets. Eg: Input: 'bbbabcd' Output: 8 'babbbabcbdbabdbdbabababaaaabaaaaaabaaabbbbbbabbbba'
332
Question : We can convert Python into HTML view site pages.(Tech Used HTML,Python ) 1 Who are you? 2 Where do you live?
 3 What should we call you? Question : Mammy, lets have some FUN With Sun Cookies Day API Question¨ Tools Needed for myself: 1 Python -
 2 Tornado -
 ...
349
Question Write a python code to check whether the entered letter is present in first half or second half of Alphabet & Print Your Output . Input Format First Line Consist of Letter. Output Format Half Where Letter First Appeared. Constraints [A-Za-z] Sample Input Password:<PASSWORD>@ Expected Output:<PASSWORD>@
408
Question_url = https://leetcode.com/problems/queue-reconstruction-by-height/
182
Question 1 Write python script that get user name, gmail account ID and password. Later, script must show all three values on the screen using "separate lines" method. Question 2 Write python script that asks user to enter the number i.e N between 1 to 15. Next script must allow user to enter only odd numbers betw...
412
Question.objects.annotate(answer_count=Count('answers')).order_by('-answer_count')[:5]
38
#Question: Write a program that reads numbers "a" and "b" from user twice. Display X when one input is negative, otherwise divide a by b once and then add the floor of final result with b and display C when answer divisible with 15, otherwise floor the answer with b. Print result a,b=int(raw_input("Enter first...
231
Question: Write a python function to count rotations required to move all zeroes towards the left end of the array. Answer: class Solution: def findNumberRotations(self, arr, s=0): c=0;p=arr.index(min(arr));q=min(arr); arr.remove(min(arr)); while((q!=0)): ...
429
Question link: https://leetcode.Question.link
158
Question: Write a procedure named "LastLetterUsingSlice" that takes two parameters: A string word called "text", and an integer called "startPos". Your procedure should return the last character in text  occurring in position between startPos and the end of the word. For example, if text = "Hello Pedro!", and startPos ...
391
import re testestr = input("enter strings") if re.match(r'\w+\@.+',testestr): print ("Valid id mail id ") else: print("Not valid iD ")
360
Question : Write a program in Python that accepts user input in terms of expression, and displays the answer in terms of number of turns required to compute the answer. Assume that answer lies between -1000 and 1000 inclusive. Assume that user enters correct expression correctly without errors. Hint: Use predefined fun...
216
us %s seconds remaining:\n%r", seconds_remaining, job.errors ) await SilverBulletQueue.pause() import asyncio import logging from silver_waffle.queue import SilverBulletQueue logger = logging.getLogger(__name__) async def job_runner(): while True: job = await SilverBulletQueu...
74
Question: Suppose I have a program written by my department. Now people don’t like programs they launch by starting their program through Run which would popup windows, instead they likes starting their program by typing in command line as shown below. MyQuestions: 1. How would you convert this acceptable python code...
178
') # Add more if f'{command} -h'.split()[0] == command: validCommands.append(command) os.chdir(root_dir) print(*sorted(validCommands,key= lambda x: len(x)),sep='\n') sravani-m/Web-Application-Security-Framework1-10 from os import walk import subprocess as sp import os root_dir...
37
"""Unit-tests for SEIR model. :Author: <NAME> III :Version: v1.0 """ import unittest from src import model from src import seir class TestSEIRParameters(unittest.TestCase): """Tests for the SEIRParameters class.""" def test_simulation_init(self): """Test constructor.""" test_param = ...
292
#Using dictionary comprehension chars={'a':'Apple', 'b':'ball','c':'cat'}; [(x,words[-x]) for x in words if x>=0 ] #Using itertools module original_dict = {'Apple': 'Organic material from fruit', 'Ball':'A ball used in sports', 'Cat':'Cat'} required_dict = ...
385
Question #1 What is an iterator? Explain its types. Give example usage. Create a range iterator that goes from 0 to 10. Print the elements: Question #2 Create a simple generator that generates numbers from 0 to infinity. Print first 10 numbers generated by your generator.
311
Question 5:Given an integer num consists of digits and possible sign ‘‘+‘‘ or ‘‘-‘‘ before exactly one ‘‘.‘‘ If the string contains negative sign, then keyword ‘‘’ will be ignored from processing further and instead ‘‘-‘‘ will be used with next integer digits. The question is to : Input a signed integerNumOutput``` If ...
76
Question Debian Pkg Question Debian Pkg Question Debian Pkg 1. Create a package named 'day1' for Debian Linux specifying following files with respective contents: /day1.py #!/usr/bin/python def hello(): print "Hello All!" Execute the package using ...
61
Question 10 Solution Question: Print the following pattern using recursion. 0 1 2 3 4 0 1 2 0 1 0 Solution: #Define a recursive function • A function should have at least one parameter • Increment rec_count variable • Print index_val until it reached to 5 • Repeat these steps until limit(5) is reached def printMechS...
120
Question 01 Question statement:With sprite rendering capabilties using PyQt5, we can something like Youtube playlists. Here we will create sprite movies consisting of frames in a folder like shown in the spectrum below: Spectrum Spectrum This question boils down to the drawback of this sprite approach. Since we have to...
274
main/migrations/0009_recipe.py # Generated by Django 3.1.13 on 2021-08-12 11:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0008_ingredient'), ] operations = [ migrations.CreateModel( name='Recipe', f...
162
Matheuscomplexo/Exerciciosex102.py0Question.py0Question.py<gh_s}% de aumento'.format(salario,((salario*percent)/100))) tars>0Question.py0Question.py def calculaAumento():" salario = float(input('Digite seu salario para descobir quanto ele ira aumentar ')) ...
207
# Generated by Django 4.0.1 on 2022-05-12 23:06 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ("organizations", "0008_rename_contactemail_organizationcontact"), ("discordbot", "0004_alter_discordmessagetracker_me...
160
Question Statement Suppose you have an e-commerce website that sells coffee. Your major goal is that customers visit as many coffee shops as possible within a given time frame that's available on your website. However, due to the increasing popularity of your website, you decided to add more coffee shops. You’ve decid...
291
sertFalse([item for item in ks if item.startswith('Z') ])0Question Answering Micro-Service (QA MSM)_GCP/tests/test_kafka_message_generator.py1-10Question Answering Micro-Service (QA MSM)_GCP/tests/test_kafka_message_generator.py import unittest from generators.KafkaQuestionsGenerator import KafkaQuestionsGenerator cla...
17
import os from ..conventions import Config class File: """Files class""" @property def config(self) -> Config: return None @property def parent(self) -> Config: parent = self.config while parent is not None: yield parent parent...
326
ss BasicTest(unittest.TestCase): def setUp(self): pass def testBaseTraversalTest(self): tv = BaseTraversalTest() tv.testBadCallToGetFingerPrintedValue() self.assertTrue(new >= old) def tearDown(self): pass if __name__== '__main__': unittest.main() arunchaganty/kbp-online1-Question-Answer...