blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
b978e78dd713e2457bdbf275679a5505e4502683 | rafal1996/CodeWars | /Array.diff.py | 385 | 3.890625 | 4 | # Your goal in this kata is to implement a difference function,
# which subtracts one list from another and returns the result.
# It should remove all values from list a, which are present in list b keeping their order.
# array_diff([1,2],[1]) == [2]
def array_diff(a, b):
return [x for x in a if x not in b]
... |
624e8c7031b4e8f3bed392a3503a32428e8526f2 | rafal1996/CodeWars | /Human Readable Time.py | 661 | 3.78125 | 4 | # Write a function, which takes a non-negative integer (seconds)
# as input and returns the time in a human-readable format (HH:MM:SS)
#
# HH = hours, padded to 2 digits, range: 00 - 99
# MM = minutes, padded to 2 digits, range: 00 - 59
# SS = seconds, padded to 2 digits, range: 00 - 59
# The maximum time never e... |
4d32c35fbc001223bf7def3087a5e0f02aef8f09 | rafal1996/CodeWars | /Merge two sorted arrays into one.py | 597 | 4.3125 | 4 | # You are given two sorted arrays that both only contain integers.
# Your task is to find a way to merge them into a single one, sorted in asc order.
# Complete the function mergeArrays(arr1, arr2), where arr1 and arr2 are the original sorted arrays.
#
# You don't need to worry about validation, since arr1 and arr2... |
12c915a3ed1908d200cb148aac64c173c363c9bc | rafal1996/CodeWars | /Convert number to reversed array of digits.py | 304 | 3.9375 | 4 | # Given a random non-negative number,
# you have to return the digits of this number within an array in reverse order.
# Example:
# 348597 => [7,9,5,8,4,3]
def digitize(n):
return [int(a) for a in str(n)][::-1]
print(digitize(35231))
print(digitize(23582357))
print(digitize(45762893920)) |
070e08fd3be86bb1ea72697e0ed1a47b27ceebc8 | rafal1996/CodeWars | /Swap Values.py | 275 | 3.53125 | 4 | # I would like to be able to pass an array with two elements to my swapValues function
# to swap the values. However it appears that the values aren't changing.
def swap_values(args):
args[0], args[1] = args[1], args[0]
return args
print(swap_values([2, 1])) |
688fe927f53058d795be239430f47cba3740e6c2 | rafal1996/CodeWars | /Twice as old.py | 469 | 3.84375 | 4 | # Your function takes two arguments:
#
# current father's age (years)
# current age of his son (years)
# Сalculate how many years ago the father was twice as old as his son
# (or in how many years he will be twice as old).
def twice_as_old(dad_years_old, son_years_old):
return abs(dad_years_old - (son_year... |
19cc7ccbec9bae1ebe59c57a9c678aeee0069f36 | tectronics/group-project-herb-cis020-1-2013 | /Code/Main user.py | 13,634 | 3.9375 | 4 | # User class
class User:
username = ""
password = ""
ID = -1
studentID = -1
def __init__(self, UserName, PassWord, StudentID):
self.username = UserName
self.password = PassWord
self.studentID = StudentID
# Driver class - Generalisation of User
class Drive... |
0f5c7105efde0d5b50391ac4fd9793ef6b670d66 | thechocobowhisperer/ubiquitious-train | /exercise.py | 4,387 | 3.828125 | 4 | import sqlite3
# from wmt import Exercise
#Change connect(thishing) to exercise.db when testing is complete
conn = sqlite3.connect(':memory:')
# conn = sqlite3.connect('exercise.db')
print("Opened database successfully")
c = conn.cursor()
c.execute("""CREATE TABLE EXERCISE (
NAME TEXT NOT NULL UNIQUE... |
cd585ca3034c4266a36f1cd06231df084cca3179 | INNOMIGHT/data-structures-using-python | /BinaryHeapImplementation.py | 2,009 | 3.578125 | 4 | class BinHeap:
def __init__(self):
self.heap_list = [0]
self.current_size = 0
def perc_up(self, current_node):
parent = current_node // 2
while parent > 0:
if self.is_less(current_node, parent):
self.swap(current_node, parent)
def is_less(self, ... |
82d69cbfa8cf269657d54e63eea33f828fd0e3fb | rahuladream/LeetCode-October-Challenge | /Day2/combination_sum.py | 632 | 3.71875 | 4 | # https://leetcode.com/explore/challenge/card/october-leetcoding-challenge/559/week-1-october-1st-october-7th/3481/
class Solution:
def combinationSum(self, candidates, target):
"""
return a list of all unique combinations of candidates where the choosen numbers sum to target.
@ Knapsack problem ... |
d88e1a7ec093c2d423413d08783ad494b813ab36 | Cyntax99/Assignment-1 | /MaskAnalysis.py | 4,179 | 3.765625 | 4 | #Prof. Berg, Assignment 1, Mohamed Yousif
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
from statistics import mean
data=pd.read_csv('mask.csv')
stateData=pd.read_csv('State_Codes.csv')
stateAbbr=pd.read_csv('abbr.csv')
# In[2]:
# gives state name of county number, accepts: county number a... |
540ba232d054297c5300247e621f441ef9b94256 | nivedithan97/EbayLand-Analysis | /ebay.py | 9,508 | 4.03125 | 4 | '''
Name: Niveditha Nagasubramanian
Assignment: Ebay(Dynamic programming)
'''
#Dynamic Programming- Bottom up Solution
def MaximizeProfit1(pdtcode,price,profit,PriceLimit):
'''
Task 1: Maximize Profit when there is no item limit and just price limit
this function determines the products to maxim... |
fefd2a747e69b10cd32e6781cd20e6be098a81fb | nobleoxford/HiGit | /RandomStuff#3.py | 138 | 3.640625 | 4 | import random
roll = random.randint(1,6)
i=0
while(i < 10):
roll = random.randit(1,6)
print(roll)
i += 1
print("Next")
|
fa3a8f018b34ca398f1d72f9ad3a3101a4e6a333 | Panjala-Thilak/DataStructures | /Graphs/bfs.py | 795 | 4.03125 | 4 | class Node(object):
def __init__(self,name):
self.name=name
self.adjacencylist=[]
self.visited=False
self.predecessor=None
class Bfs(object):
def bfs(self,start):
queue=[]
queue.append(start)
start.visited=True
while queue:
... |
5b0ff71e24e669d5e82d4e7010bf36b969c24881 | rabhatna/CM146 | /Pa3/src/mcts_modified.py | 4,953 | 3.625 | 4 |
from mcts_node import MCTSNode
from random import choice
from math import sqrt, log
num_nodes = 1000
explore_faction = 2.
def traverse_nodes(node, board, state, identity):
""" Traverses the tree until the end criterion are met.
Args:
node: A tree node from which the search is trave... |
b587de0eec961113571a8481238a59ce918cebbc | iiipod/py-learn | /py4kid/11.5_square.py | 215 | 3.59375 | 4 | import turtle
t = turtle.Pen()
def mysquare(size):
for x in range(1, 5):
t.forward(size)
t.left(90)
mysquare(80)
t.reset()
mysquare(25)
mysquare(50)
mysquare(75)
mysquare(100)
mysquare(125)
|
e4b8ba0005fb230992c449b364375640fe86edae | keerthi-kundapur/hactoberfest-Projects-2020 | /Hackerrank-Python/FindingThePercentage.py | 467 | 3.671875 | 4 | def find_avg_marks(student_marks,query_name):
avg_marks=sum(student_marks[query_name])/len(student_marks[query_name])
return avg_marks
if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
... |
8dd877de56b3bc1fd5367be11b3ed0d96874b7e1 | mrnettek/Python | /test_for_palindrome.py | 334 | 3.546875 | 4 | # MrNetTek
# eddiejackson.net/blog
# 10/14/2019
# free for public use
# free to claim as your own
def is_palindrome(input):
input = input.lower()
return input[::-1] == input
print("\x1b[2J")
print("Father")
print(is_palindrome("Father"))
print "\n"
print("Dad")
print(is_palindrome("Dad"... |
060a88ef713089b6c19649d7ce24d0e33a6d0928 | Helena23/python | /soma.py | 174 | 3.921875 | 4 | numero1=int(input("Digite um número inteiro:"))
numero2=int(input("Digite outro número inteiro:"))
soma=numero1+numero2
print("O resultado da soma é:{}".format(soma))
|
69857403409270b2dc727ef3ad289daa99bb7e3f | martingascon/MITx6_1x_Introduction_to_Computer_Science_and_Programming_Using_Python | /Programs/radiationExposure.py | 1,102 | 4.09375 | 4 | def f(x):
import math
return 10*math.e**(math.log(0.5)/5.27 * x)
def radiationExposure(start, stop, step):
'''
Computes and returns the amount of radiation exposed
to between the start and stop times. Calls the
function f (defined for you in the grading script)
to obtain the value of the f... |
f89d9693703a06cb81a3defec1b263eab7c157dc | martingascon/MITx6_1x_Introduction_to_Computer_Science_and_Programming_Using_Python | /Programs/Credit_card_Payment.py | 483 | 3.578125 | 4 | balance = 5000
monthlyPaymentRate = 0.02
annualInterestRate=0.18
mon = 0
totalPaid = 0
while mon <12:
minPay = monthlyPaymentRate * balance
unpaidBal = balance - minPay
totalPaid += minPay
balance = unpaidBal*(1 + annualInterestRate/12.0)
mon += 1
print "Month: %2d" % (mon)
print "Minimum ... |
cba4ac861361f48ed9b2c3805c56602a9d65cc12 | atrivedi397/MachineLearning | /Naive_Bayes/naive_bayes_anchal.py | 1,646 | 3.546875 | 4 | # Import LabelEncoder
import pandas as pd
# Import Gaussian Naive Bayes model
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import confusion_matrix
from sklearn import preprocessing
from sklearn.metrics import classification_report
from sklearn.metrics import accuracy_score
# creating labelEncoder f... |
10fc0b781648bda0efedbaf9f1e5e5f8acf0fe90 | diegoinacio/machine-learning-notebooks | /Machine-Learning-Fundamentals/regression__utils.py | 2,840 | 3.65625 | 4 | import numpy as np
def correlation(X, Y):
'''
Correlation function
'''
N = X.size
mu_X = X.sum()/N
mu_Y = Y.sum()/N
cov = ((X - mu_X)*(Y - mu_Y)).sum()/N
sigma_X = X.std()
sigma_Y = Y.std()
return cov/(sigma_X*sigma_Y)
######################
### Synthetic Data ###
#############... |
9998009659bc70720c63ab399c45fb8adafe5e2b | sam-calvert/mit600 | /problem_set_1/ps1b.py | 1,827 | 4.5 | 4 | #!/bin/python3
"""
Paying Debt Off In a Year
Problem 2
Now write a program that calculates the minimum fixed monthly payment needed in order pay
off a credit card balance within 12 months. We will not be dealing with a minimum monthly
payment rate.
Take as raw_input() the following floating point numbers:
1. ... |
82ba57603b4f95941ba5d85e1b47189543e7eb7c | IKuuhakuI/Python_Test | /main.py | 1,255 | 3.796875 | 4 | # Importa os outros programas
import game
import send_questions
# Mensagem de entrada
print("Bem Vindo ao jogo de Perguntas e Respostas!")
print()
print("O objetivo e ver quem consegue acertar o maximo de perguntas sem errar!")
print("Voce acha que consegue quebrar o recorde?")
print()
print("Ou entao, voce pode contr... |
e41289d780dc63f3f737f51920298cf8524104be | AHaliq/bombMaze | /main.py | 3,677 | 3.625 | 4 | #!/usr/bin/env python3
import queue
# IVE ONLY KEYED IN THE FIRST MAZE
maze_walls = {
((0,1),(5,2)):
(
[(1,0),(4,0),(5,0),(2,1),(3,1),(4,1),(1,2),(4,2),(1,3),(2,3),(3,3),(4,3),(1,4),(4,4)],
# coordinates of tiles with inner bottom walls
[(2,0),(0,1),(2,1),(0,2),(2,2),(0,3),(3,3),(2,4),(4,4),(1... |
c806a5d9275a6026fb58cc261b8bfd95c1d66b90 | keshavkummari/python-nit-7am | /Operators/bitwise.py | 1,535 | 4.71875 | 5 | '''--------------------------------------------------------------'''
# 5. Bitwise Operators :
'''--------------------------------------------------------------'''
"""
Bitwise operator works on bits and performs bit-by-bit operation.
Assume if a = 60; and b = 13;
Now in binary format they will be as follows :
a = 0011... |
910fe52e3d7eafcec15c6d5e31cc8d33bd087942 | keshavkummari/python-nit-7am | /DataTypes/Strings/unicodes.py | 2,461 | 4.1875 | 4 | Converting to Bytes. The opposite method of bytes.decode() is str.encode(),
which returns a bytes representation of the Unicode string,
encoded in the requested encoding.
The errors parameter is the same as the parameter of the
decode() method but supports a few more possible handlers.
UTF-8 is one such ... |
d264f225a8bab8cb69c1e782748de43ecfc6f429 | keshavkummari/python-nit-7am | /DataTypes/List/Min_Max_Methods.py | 395 | 3.75 | 4 | #!/usr/bin/python
aCoolList = ["superman", "spiderman", 1947]
oneMoreList = [22, 34, 56, 78, 98]
aCoolTuple = ("StreetBob", "Dyna", "Iron883", 1200)
# important Function
print (len(aCoolList))
# finding Max
print (max(oneMoreList))
#print (max(aCoolList))
# finding min
print (min(oneMoreList))
#print (min(aCoolL... |
f5c67e47e4140b3d92226fe3df69055c3a0c3d85 | keshavkummari/python-nit-7am | /Operators/arithmetic.py | 709 | 4.53125 | 5 | '''--------------------------------------------------------------'''
# 1. Arithmetic Operators:
'''--------------------------------------------------------------'''
"""
1. + = Addition
2. - = Subtraction
3. * = Multiplication
4. / = Division
5. % = Modulus
6. ** = Exponent
7. // = Floor Division
"""
# Ex... |
5df22e2d5a8a355039ca078214780b7cb81d510b | keshavkummari/python-nit-7am | /decision_making/if_else.py | 323 | 3.8125 | 4 | #!/usr/bin/python
a_1 =int(input("Enter a Number Value: "))
if a_1 == 200:
print("1 - True expression value")
print(a_1)
else:
print("1 - False expression value")
print(a_1)
var = 50
if ( var != 100 ) : print("If Block, Value of expression is 100")
else: print("Value of var is not 100")
print("Good bye... |
590a73a02a9b45ef5a2e2da924fc7fc40ee3c728 | keshavkummari/python-nit-7am | /DataTypes/Strings/count_1.py | 360 | 3.921875 | 4 | #!/usr/bin/python
#0123456789
str1 = "Welcome to python world python and python"
sub = "o"
print(len(str1))
print ("str1.count(sub, 4, 40) : ", str1.count(sub, 0, 40))
print ("str1.count(sub, 4, 40) : ", str1.count(sub, -5,-1))
sub1 = "python"
print ("str1.count(sub1) : ", str1.count(sub1))
print ("str1... |
e1bd386db1b3173b3b09451af5a9fa18878d1fd6 | keshavkummari/python-nit-7am | /DataTypes/Strings/Python_Strings_Functions.py | 10,307 | 4.4375 | 4 | Python Strings:
Strings are amongst the most popular types in Python.
We can create them simply by enclosing characters in quotes.
Python treats single quotes the same as double quotes.
Creating strings is as simple as assigning a value to a variable.
For example :
var1 = 'Hello World!'
var2 = "Python Pr... |
f2da3c60906b8f5877da860b9871a0bfb306e0ff | keshavkummari/python-nit-7am | /DataTypes/Strings/PYTHON_STRINGS_METHODS.py | 6,874 | 4.4375 | 4 | '''****************** PYTHON STRING METHODS ******************************'''
# 31. split() Method :
"""
Split method is used to break a given string by the specified delimiter like a comma.
Syntax : str.split(str=" ", num=string.count(str)).
str -- This is any delimeter, by default it is space.
num -- this i... |
8ecf94ded53093ec4a5a44b176797532db13265a | keshavkummari/python-nit-7am | /decision_making/decisionmakingNotes.py | 7,463 | 4.34375 | 4 | ********************************************************************
# Python Decision Making using Control Flow or Conditional Statements in Python:
'''
Decision making is anticipation of conditions occurring while execution of the program and
specifying actions taken according to the conditions.
Decision structur... |
dc79c73d8e48ff9fcfdda2ff8e32d3a856c30afa | JasonVann/CrackingCodingInterview | /LeetCode/Trie.py | 4,435 | 4.15625 | 4 | class TrieNode:
def __init__(self):
self.child = [None]*26
self.is_end_of_word = False
class Trie_Recur:
# Maybe better to use Trie and TrieNode, not a nested Trie class
# http://www.geeksforgeeks.org/trie-insert-and-search/
def __init__(self):
"""
Initialize your data ... |
bf409ca3922e9452c0603681f8d23247a12705d4 | JasonVann/CrackingCodingInterview | /LeetCode/Ex600/Ex677.py | 2,669 | 3.734375 | 4 | class MapSum_Hash(object):
def __init__(self):
self.map = {}
self.score = collections.Counter()
def insert(self, key, val):
delta = val - self.map.get(key, 0)
self.map[key] = val
for i in xrange(len(key) + 1):
prefix = key[:i]
self.score[prefix] +... |
5a9110cdddc5f7f0b35582a302496d2b17d394c5 | JasonVann/CrackingCodingInterview | /LeetCode/Ex0/Ex7.py | 453 | 3.78125 | 4 | class Ex7(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
pre = ''
if x < 0:
pre = '-'
x = -x
#print x, str(10)
all = str(x)
res = ''
for i in all:
res = i + res
res = int(pre ... |
98abc2d65b51b306d45e52442ff4db5b934099e4 | JasonVann/CrackingCodingInterview | /LeetCode/Ex0/Ex73.py | 1,653 | 3.625 | 4 | class Ex73(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
for i in range(len(matrix)):
row = matrix[i]
for j in range(len(row)):
if matrix... |
881b42d857ef35b5086364dc507602a2ef84b2ca | JasonVann/CrackingCodingInterview | /LeetCode/Ex300/Ex336.py | 7,071 | 3.59375 | 4 | class Solution(object):
# Trie: https://discuss.leetcode.com/topic/39585/o-n-k-2-java-solution-with-trie-structure-n-total-number-of-words-k-average-length-of-each-word/2
def palindromePairs_n2(self, words):
"""
:type words: List[str]
:rtype: List[List[int]]
"""
# O(... |
f589088dd1de08e9b378cae5130291a03dfcb9ad | JasonVann/CrackingCodingInterview | /LeetCode/Ex0/Ex80.py | 1,389 | 3.59375 | 4 | class Ex80(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
if n <= 2:
return n
p1 = 1
p2 = n - 1
i = 1
cur = nums[0]
to_remove = False
... |
4c84f8b94a394c86b2d9b3675a2711e2eccf3a15 | JasonVann/CrackingCodingInterview | /CCI/C7_ObjectOrientedDesign/Ex7.11.py | 792 | 3.546875 | 4 | class FileSystem():
def __init__(self):
self.dir = []
def create_file(self, name):
file = File(name)
self.dir.append(file)
def search(self, name):
# Trie or Linear Search
pass
def delete(self, name):
file = self.search(name)
self.dir.remove(file... |
8d94e57b27d65a91ffe055dde983410d00455d94 | JasonVann/CrackingCodingInterview | /CCI/C10_SortingAndSearching/Ex10.2.py | 412 | 3.796875 | 4 | def group_anagrams(A):
lookup = {}
for a in A:
temp = ''.join(sorted(a))
if temp not in lookup:
lookup[temp] = [a]
else:
lookup[temp] += [a]
i = 0
for k, v in lookup.items():
for temp in v:
A[i] = temp
i += 1
return A
d... |
d7d1c4205588a0c59b9b4236d82bd9f5b69f3df8 | JasonVann/CrackingCodingInterview | /CCI/C4_TreesAndGraphs/min_heap.py | 1,381 | 3.90625 | 4 | class Min_Heap():
def __init__(self):
self.data = []
self.size = 0
def insert(self, val):
# Bubble up
self.data.append(val)
index = self.size
self.size += 1
while index > 1 and val < self.data[self.parent(index)]:
self.data[index], self.data[s... |
e9fa44232de9615496fa918c048c7ac7e3d575a0 | JasonVann/CrackingCodingInterview | /CCI/C5_BitManipulation/Ex5.8.py | 762 | 3.59375 | 4 | def draw_line(A, w, x1, x2, y):
# Draw a line from (x1, y) to (x2, y)
# A is a list of byte
row = w/8
y_start = row*y
x_start = y_start + x1//8 # first full byte
if x1 % 8 != 0:
x_start += 1
#k1 = 1 << (x1%8) - 1
all_ones = 2**8-1
last_full_byte = x2 / 8
if x2 % 8 != 7:
... |
ef891a957a0bc1ff3f7bc9eec581b8f9387b3b58 | mrasap/AIVD2018 | /Teaser/src/spellchecker/spellchecker.py | 499 | 3.59375 | 4 | class Spellchecker:
def __init__(s):
with open('/usr/share/dict/nederlands', encoding='utf-8') as data_file:
s.nl = set(data_file.read().splitlines())
def intersect(s, word: [str]) -> [str]:
return [x for x in word if x in s.nl]
def intersect_amount(s, word: [str]) -> int:
... |
5ef689dc52b33d1f4ebac52edae13da52de0fca9 | longshirong/python | /LeetCode/dynamic/classic/uniquePaths.py | 683 | 3.921875 | 4 | from typing import List
"""
62. 不同路径
https://leetcode-cn.com/problems/unique-paths/
输入: m = 3, n = 2
输出: 3
解释:
从左上角开始,总共有 3 条路径可以到达右下角。
1. 向右 -> 向右 -> 向下
2. 向右 -> 向下 -> 向右
3. 向下 -> 向右 -> 向右
"""
def uniquePaths(m: int, n: int) -> int:
dp = [[0] * n for _ in range(m)]
for i in range(m):
... |
f66cb7f3a42ad34b99563cb45a1f405818707491 | longshirong/python | /LeetCode/number/findBestValue.py | 845 | 3.5625 | 4 | """
1300. 转变数组后最接近目标值的数组和
https://leetcode-cn.com/problems/sum-of-mutated-array-closest-to-target/
输入:arr = [4,9,3], target = 10
输出:3
解释:当选择 value 为 3 时,数组会变成 [3, 3, 3],和为 9 ,这是最接近 target 的方案
"""
import bisect
from typing import List
class Solution:
def findBestValue(self, arr: List[int], target: int)... |
7bea936608bfba90e1148145eef1d4bfde694652 | mraharrisoncs/python-basics | /perimeter1.py | 160 | 4.09375 | 4 | length=input("length of side?")
lenint=int(length)
perimeter=lenint * 4
print("The perimeter of a square with side of {0} is {1}".format(lenint,perimeter))
|
5ab12d2debb1675355acbc0982e980882e6222d3 | djung460/pythonScripts | /mapIt.py | 668 | 3.71875 | 4 | #! python3
# mapIt.py - Launches a map in the browser using an address from the
# command line or clipboard.
import webbrowser, sys, pyperclip, requests, pyperclip, bs4
from selenium import webdriver
if len(sys.argv) > 1:
# Get address from command line.
address = ' '.join(sys.argv[1:])
else:
# Get address f... |
f828c6a66288f8e83538c536640d5529942909be | mhall0721/techdegree_project_2 | /atbash.py | 980 | 3.84375 | 4 | from ciphers import Cipher
class Atbash(Cipher):
def __init__(self, *args, **kwargs):
super().__init__()
for key, value in kwargs.items():
setattr(self, key, value)
def encrypt(self, text):
'''Atbash encryption:
Matches letter to it's corresponding letter in a rev... |
8a2e30d80039516f6efec4ed1bad0b4483d96ce6 | daysgone/foobar | /level1.py | 387 | 3.796875 | 4 | import math
def answer(n):
primes = ''
for num in range(1, 101):
if all(num % i != 0 for i in range(2, int(math.sqrt(num)) + 1)):
primes += str(num)
print primes
return primes[n+1:n+6]
#print answer(3)
'''
noprimes = [j for i in range(2, 8) for j in range(i*2, 100, i)]
primes ... |
ce3b26e69ac684c440364c89512f654255e54aa9 | Mirlan1521/pythone_kurs_2 | /Home_Works_month_2/Home_Work_8/DZ#8.py | 4,774 | 4.03125 | 4 | import sqlite3
class Teacher:
def __init__(self):
self.connection = sqlite3.connect('HW8.sqlite3')
def create_table(self):
cursor = self.connection.cursor()
try:
cursor.execute('create table teacher('
'id integer primary key unique, name text, s... |
c81ca7b213c5b8f442f5a1169be00a72874ecd7a | mirajbasit/dice | /dice project.py | 1,152 | 4.125 | 4 | import random
# do this cuz u have to
def main():
# .lower makes everything inputted lowercase
roll_dice = input("Would you like to roll a dice, yes or no? ").lower()
# add the name of what is being defined each time
if roll_dice == "no" or roll_dice == "n":
print("Ok, see you later ")
... |
d655fe19b17ceadc6e5478a8e847225b8846ac9d | mattglibota/election-analysis | /PyPoll_Challenge.py | 4,901 | 3.921875 | 4 | #Data we need to retreive
#1. Total number of votes cast
#2. complete list of counties which received votes
#3. percentage of votes each county had
#4. calculate largest county turnout
#5. complete list of candidates who received votes
#6. percentage of votes each candidate won
#7. total number of votes each candidate ... |
c0d3a7dc109e8c8b45feb6490f1c413a6f3fb211 | Johngitonga/HangMan-Game | /HangMan.py | 1,938 | 4.09375 | 4 | """
create a list of words
pick a random word from list
print a dash for each letter
prompt user to guess a letter
if letter in word, replace all occurencies in correct positions.
print previously correct guessed letters together with remaining dashes
prompt user for another guess.
if letter not in word; error message... |
d13d9e5096bd9ba71e0744b9e17bb3d825b67c7d | mcranwill/RUDI_Interpreter | /main.py | 2,261 | 3.875 | 4 | # Driver program for RUDI Interpreter that reads in a file and
# execute it per the RUDI grammar. Program is written against
# the Python3.5 language standard and is run like
# python main.py <input_file> where input_file is like test.rudi
#
# RUDI Interpreter Final Project- Fall 2016
# Data Structures & A... |
53d5d64be2ba5861b854bd279f366e54f681235e | OscaRoa/intro-python | /mi_primer_script.py | 749 | 4.125 | 4 | # Primera sección de la clase
# Intro a scripts
"""
Primera sección de la clase
Intro a scripts
"""
# Segunda sección
# Estructuras de control
if 3 > 5 and 3 > 2:
print("Tres es mayor que cinco y que dos")
# edad = 18
# if edad > 18:
# print("Loteria!")
# elif edad == 18:
# print("Apenitas loteria!")
# e... |
387e100b94b3a8817d3f4d46679548629f2702a0 | MandyKwok/Helper | /input_data/data_generation.py | 528 | 3.71875 | 4 | import random
import datetime
def generate_N_random_date(N, start, end):
"""
This function will return N random datetime objects between two datetime
objects.
"""
delta = end - start
int_delta = (delta.days * 24 * 60 * 60) + delta.seconds
result = []
for i in range(N):
ran... |
b721c7e8157a871cb32ba7491b093bfb43ae9bbd | Jay87682/leetcode-python | /2_add_two_sum/listnode.py | 1,056 | 3.921875 | 4 | from node import Node
class ListNode():
""" Create a list of none-negative integer.
Each node should contain a value with one digital (<10)
Attributes:
start: Star node of the list
end: End node of the list
"""
def __init__(self):
""" Init ListNode """
self.start =... |
f58b89d169650839c43e0b716b877f6661245f48 | vnBB/python_basic_par1_exersises | /exercise_5.py | 283 | 4.375 | 4 | # Write a Python program which accepts the user's first and last name and print them in
# reverse order with a space between them.
firstname = str(input("Enter your first name: "))
lastname = str(input("Enter your last name: "))
print("Your name is: " + lastname + " " + firstname) |
295f1eb12d3d9781a33ab1dca4a1ca44a9478a12 | stefaniacerboni/Hash | /hash.py | 4,072 | 3.953125 | 4 | from LinkedList import LinkedList
from LinkedList import Node
class _Hash:
# aggiungo underscore, per convenzione un nome preceduto da underscore
# dovrebbe essere trattato come una parte non pubblica dall'API
def __init__(self, m):
self.m = m
self.list = [None] * m
self.collision ... |
f562648ec7df6b812f46ff4090055c8d80b4608f | Marat200/python_task | /задание 2 к уроку 2.py | 357 | 3.9375 | 4 | my_list = []
num = int(input(f'Введите количество элементов списка: '))
for i in range(num):
new_el = input(f'Введите новый элемент списка: ')
my_list.append(new_el)
print(my_list)
for a in range(1, num, 2):
my_list[a-1], my_list[a] = my_list[a], my_list[a-1]
print(my_list) |
577db2dbd3577dfcc197d22ac9474e820400c086 | Marat200/python_task | /home work 5/work5.py | 756 | 4.03125 | 4 | выручка = float(input("Введите выручку фирмы "))
издержки = float(input("Введите издержки фирмы "))
if выручка > издержки:
print(f"Фирма работает с прибылью. Рентабельность выручки составила {выручка / издержки:.2f}")
workers = int(input("Введите количество сотрудников фирмы "))
print(f"прибыль в расчете на... |
15c10d517143c719ebf2d2faaf182f088f11cfa7 | nicoleczerepak/CS104-03 | /testaverage.py | 214 | 3.921875 | 4 | numberofscore - 0
score = 0
score2= 0
total= 0
average= 0
scorecount= 0
score1= int(input("Please enter a test score"))
score2= int(input("Please enter a test score"))
average= (score1+score2)/2
print(average)
|
2bb27bed76ce5cf38573ad7643112c15fbd86732 | chordw/pythonstudy | /code/base/_0_HelloWord.py | 192 | 3.765625 | 4 | print('你的名字是什么?')
name = input()
print('你好,' + name + '!')
print('你在干什么呢?')
what = input()
def hehe():
return "浪费生命"
print(what + hehe())
|
4f1db5440a48a15f126f4f97439ef197c0c380ab | mynameischokan/python | /Strings and Text/1_4.py | 1,915 | 4.375 | 4 | """
************************************************************
**** 1.4. Matching and Searching for Text Patterns
************************************************************
#########
# Problem
#########
# We want to match or search text for a specific pattern.
#########
# Solution
#########
# If the text you’re... |
8c556ffbdec35133b9d410fe771a3f473fda2bca | mynameischokan/python | /Iterators and Generators/1_6.py | 1,200 | 4.09375 | 4 | """
*******************************************************
**** 4.6. Defining Generator Functions with Extra State
*******************************************************
#########
# Problem
#########
# You would like to define a generator function,
# but it involves extra state that you would like to expose to the u... |
81c12a65a42c018ea36114c3f0b1e5c19b14c0d4 | mynameischokan/python | /Strings and Text/1_10.py | 850 | 3.796875 | 4 | """
************************************************************
**** 1.10. Working with Unicode Characters in Regular Expressions
************************************************************
#########
# Problem
#########
# You are using regular expressions to process text,
# but are concerned about the handling of U... |
ee3c46dff28ef31e47eb88fa1effb1e10dfa72f2 | mynameischokan/python | /Iterators and Generators/1_12.py | 1,033 | 3.875 | 4 | """
****************************************************
**** 4.12. Iterating on Items in Separate Containers
****************************************************
#########
# Problem
#########
# You need to perform the same operation on many objects,
# but the objects are contained in different containers,
# and you’d... |
2005dfcd3969edb4c38aba4b66cbb9a5eaa2e0f2 | mynameischokan/python | /Data Structures and Algorithms/1_3.py | 1,459 | 4.15625 | 4 | '''
*************************************************
**** Keeping the Last N Items
*************************************************
#########
# Problem
#########
# You want to keep a limited history of the last few items seen during iteration
# or during some other kind of processing.
#########
# Solution
#######... |
383dbeb58575c030f659e21cfe9db4de0f3b4043 | mynameischokan/python | /Files and I:O/1_3.py | 917 | 4.34375 | 4 | """
*************************************************************
**** 5.3. Printing with a Different Separator or Line Ending
*************************************************************
#########
# Problem
#########
- You want to output data using print(),
but you also want to change the separator charact... |
5b72d935745339f5534a414e96380b3d2fc78fbf | mynameischokan/python | /Data Structures and Algorithms/1_11.py | 728 | 3.8125 | 4 | """
************************************************************
**** 1.11. Naming a Slice
************************************************************
#########
# Problem
#########
# Your program has become an unreadable mess
# of hardcoded slice indices and you want to clean it up.
#########
# Solution
#########
... |
1bd70d523462fb7361827ebd700301ab2932c1c7 | mynameischokan/python | /Files and I:O/1_7.py | 625 | 4.03125 | 4 | """
**************************************************
**** 5.7. Reading and Writing Compressed Datafiles
**************************************************
#########
# Problem
#########
# You need to read or write data in a file with gzip or bz2 compression.
#########
# Solution
#########
# The gzip and bz2 modu... |
de1aa481776514ff6cee06f078272c2276a14b7e | anviaggarwal/assignment-16 | /ass 16.py | 538 | 3.734375 | 4 | #Q.1
import pymongo
client=pymongo.MongoClient()
database=client['Students']
print('STUDENTS DATABASE CREATED')
collection=database['Student Data']
print('Students data table has been created')
#Q.2-
#Q.3
for i in range (1,11):
print('Enter Detail Of Student {}:'.format(i))
name=input('Name:')
marks=int(inp... |
6dfbf466e6a2697a3c650dd7963e8b446c3ebbdd | paulprigoda/blackjackpython | /button.py | 2,305 | 4.25 | 4 | # button.py
# for lab 8 on writing classes
from graphics import *
from random import randrange
class Button:
"""A button is a labeled rectangle in a window.
It is enabled or disabled with the activate()
and deactivate() methods. The clicked(pt) method
returns True if and only if the button is enabled ... |
c1f2a315792ff3ac90166a85d199e2940305a5cd | ojshj/duoduo_git | /test_question/6 字符串到字典.py | 198 | 4.3125 | 4 | #6 字符串到字典
#将字符串:"k:1|k1:2|k2:3|k3:4",处理成 python 字典:{'k':'1', 'k1':'2', 'k2':'3','k3':'4' }
dict={}
dict[k]=1
dict[k1]=2
dict[k2]=3
dict[k3]=4
print(dict) |
1bb39936e70ffc152395c35e4477ca9e1e8488b0 | ojshj/duoduo_git | /basic/string.py | 401 | 3.78125 | 4 | a = "12345678"
#获取子字符串的位置
print(a.find('3'))
#split
a = "1 2 3 4 5 6"
b = a.split(" ")
print(b)
#打印变量的类型
print("type of a is:", type(a))
print("type of b is:", type(b))
#切片
c = "1234567890"
#打印第3-第5个字符
#print(c[3:5])
#print(c[:-1])
print(c[-5:-1])
#字符串拼接
a1 = "1111"
a2 = "22222"
c = a1+a2
... |
5af62d4aa5bc5786448ecc89a4fcf037b1ad352e | ojshj/duoduo_git | /test_question/2 字符串反转.py | 136 | 3.9375 | 4 | #2 字符串反转
#s = "willing to suffer"
#输出反转后的字符串
s = "willing to suffer"
l3=list(s)
l3.reverse()
print(l3) |
21c33a73ceb9a4a1bed83ede274d69df632b637b | ojshj/duoduo_git | /test_question/6++字符串到字典.py | 715 | 3.921875 | 4 | #6 字符串到字典
#将字符串:"k:1|k1:2|k2:3|k3:4",处理成 python 字典:{'k':'1', 'k1':'2', 'k2':'3','k3':'4' }
dict={}
dict[k]=1
dict[k1]=2
dict[k2]=3
dict[k3]=4
print(dict)
#不是这样, 应该是
#s = "k:1|k1:2|k2:3|k3:4"
#写个函数, 输入s ,输出这个字典
s = "k:1|k1:2|k2:3|k3:4"
dict1=eval(s)
print(dict1)
#根本跑不起来 糊弄自己呢
#提示 先风格为一个list [... |
e715d6fbf0c8c2c9b7356278d735fbeea36171ef | ojshj/duoduo_git | /euler/1 Multiples of 3 and 5_for_version.py | 164 | 3.828125 | 4 | sum=0
for i in range(1000):
if i%3!=0 and i%5!=0:
pass
else:
sum+=i
print("current i is", i)
print(sum)
|
ab96cb7976bbe4983efed3a028aec8ea547ceef3 | ojshj/duoduo_git | /test_question/4 绝对值排序.py | 161 | 3.65625 | 4 | #4 绝对值排序
#List = [-2, 1, 3, -6],如何实现以绝对值大小从小到大将 List 中内容排序
list=[-2,1,3,-6]
print sorted(map(abs,list)) |
8ee50a412b4cb65b229f52be4cdbad0852b4bd88 | rajaadil07/Guessing-Game | /GuessingGame.py | 851 | 4.09375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[18]:
import random
random_number = random.randint(1,100)
guesses = 0
try:
print("The Guessing Game")
print("Enter a number (1-100)\nThree Guesses Available!\n")
while guesses < 3:
guess = int(input("Guess: "))
if guess == random_number:
... |
4cf1bed209d9a2e79c58ef3187e98b8ddfb8c348 | akshat-52/FallSem2 | /act1.29/9.py | 241 | 3.90625 | 4 | set1={10, 20, 30, 40, 50, 60}
print("The Original Set : ",set1)
print("Maximum Number in Set : ",max(set1))
print("Minimum Number in Set : ",min(set1))
print("The Sorted List : ",sorted(set1))
print("The Sum of the List : ",sum(set1))
|
66e92cca9b314e1a5007e9527dbb92a884c133f6 | akshat-52/FallSem2 | /act1.26/tuple_as_list.py | 236 | 3.921875 | 4 | tupl=("MATHS","PHYSICS","COMPUTER")
print("THE ORIGINAL TUPLE")
print(tupl)
print("\n")
a=list(tupl)
print("TUPLE AS A LIST")
print(a)
print("\n")
a[1]="HISTORY"
tupl=tuple(a)
print("TUPLE AFTER CHANGING ELEMENT")
print(tupl) |
bf694c58e1e2f543f3c84c41e32faa3301654c6e | akshat-52/FallSem2 | /act1.19/1e.py | 266 | 4.34375 | 4 | country_list=["India","Austria","Canada","Italy","Japan","France","Germany","Switerland","Sweden","Denmark"]
print(country_list)
if "India" in country_list:
print("Yes, India is present in the list.")
else:
print("No, India is not present in the list.") |
d71aa82e520cce8570baf26c998779415e4b9ac0 | akshat-52/FallSem2 | /act1.19/1m.py | 221 | 3.9375 | 4 | country_list=["India","Austria","Canada","Italy","Japan","France","Germany","Switzerland","Sweden","Denmark","Egypt","Algeria","Burma","Madagascar","Sri Lanka"]
for i in country_list:
if len(i)<=5:
print(i) |
f04933dd4fa2167d54d9be84cf03fa7f9916664c | akshat-52/FallSem2 | /act1.25/3.py | 730 | 4.125 | 4 | def addition(a,b):
n=a+b
print("Sum : ",n)
def subtraction(a,b):
n=a-b
print("Diffrence : ",n)
def multiplication(a,b):
n=a*b
print("Product : ",n)
def division(a,b):
n=a/b
print("Quotient : ",n)
num1=int(input("Enter the first number : "))
num2=int(input("Enter the second n... |
a791a2b844a92e8e62bcaa249395ba2969b1f29c | MrNiebieski/scatter_compare | /scatter_compare/tracer2.py | 1,227 | 3.515625 | 4 | import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate
from scipy.interpolate import interp1d
def isbetween(left,right,test):
return (left-test)*(test-right)>=0
def interpolate(x1,y1,x2,y2,x,y):
#print x1,x,x2
#print y1,y,y2
return (x*(y2-y1)+(x2*y1-x1*y2)-y*(x2-x1))/(x2-x1)
with open('... |
736fcd322c46ef6c588dd258ab9acb0c3791025a | remilvus/Compiler | /src/ast/tree_printer.py | 5,461 | 3.5 | 4 | from src.ast.ast import *
def add_to_class(cls):
def decorator(func):
setattr(cls, func.__name__, func)
return decorator
def print_indent(indent):
for i in range(indent):
print("| ", end="")
class TreePrinter:
def __init__(self):
pass
@staticmethod
@add_to_class(P... |
e13fffe7ae4270c4ec4674b927c3cb8671a1c89f | Oobi12/LED-project | /testtinkiner.py | 2,150 | 3.515625 | 4 | # Write your code here :-)
import sys
import os
from time import sleep
from tkinter import *
from tkinter import messagebox
# initialise main window
def init(win):
win.title("LED application")
win.minsize(500, 100)
btn.pack()
btn2.pack()
btn3.pack()
btn4.pack()
btn5.pack()
# button callb... |
fa412fbce1dc65b4a41a2e4d93c279d31b8458b3 | bdxbot/iyocgwp | /bk_hangman_enhanced.py | 5,822 | 3.8125 | 4 | import random
# create a list with all images for reaper
REAPER = ['''
=====''', '''
O
=====''', '''
O
|
=====''', '''
O
/|
=====''', '''
O
/|\\
=====''', '''
O
/|\\
/
=====''', '''
O
/|\\
/ \\
=====''', '''
O - GAME OVER
(|)
/ \\
=====''','''
O
'|)
/ \\
====='''... |
e5edc8241567c064b0245171561d2f5b3ec60589 | IsraMejia/AnalisisNumerico | /c5-Interpolacion(RFalsa).py | 1,157 | 4 | 4 |
import numpy as np
print('\n\tInterpolacion de valores o regla falsa \n')
def rf(a,b): #Regla falsa
return b-f(b)*(a-b) / ( f(a) - f(b))
def f(x):
return np.power(x, 3) + 3*np.power(x,2) - 1
a = -1
b=0
tolerancia = 0.1
cabecera = "{:<8} {:<10} {:<10} {:<10} {:<10} {:<10} {:<10}".format( 'It' , 'a... |
41b18bcd2865baaaf6f965903c5faa4bc2db1203 | IsraMejia/AnalisisNumerico | /c10-LU.py | 1,335 | 3.65625 | 4 | #Método LU
import numpy as np
print('Metodo de LU')
def descLU(A,b):
A=np.array(A,dtype=np.float32)
b=np.array(b,dtype=np.float32)
print("A=\n",A)
print("b=\n",b)
m=len(b)#tamño de la matriz b
x=np.zeros([m,1])
y=np.zeros([m,1])
#Matriz U
U=np.zeros([m,m])#Matriz U
#Matriz L
L=np.ident... |
a64626fdfda7a04f7fc5bf1429dc0bb989c27e9e | IsraMejia/AnalisisNumerico | /c5-NewtonRapson.py | 732 | 3.5625 | 4 | import numpy as np
print('\n\t\tNewton Rapson \n')
#Funcion original
def f(x):
return np.exp(-x)-x
#Derivada de la funcion
def df(x):
return -np.exp(-x)-1
xi = 1 #Punto Inicial
tol = 0.00001
it=1
cabecera= "{:<8} {:<8} {:<8} {:<8}".format('Itera', 'x_i', 'x_i+1', 'Eabs')
print(cabecera)
while True:
if( df... |
132ef9c4837fb9658914a43db7ff91c1510bad07 | apacha/OMR-Datasets | /omrdatasettools/Point2D.py | 307 | 3.8125 | 4 | class Point2D():
"""A point in a 2-dimensional Euclidean space. """
def __init__(self, x: float, y: float) -> None:
super().__init__()
self.x = x
self.y = y
def __eq__(self, o: object) -> bool:
return isinstance(o, Point2D) and self.x == o.x and self.y == o.y
|
9749c1b74feda3e450137f0bf9dbcaea0789ff51 | AndreyDolgodvorov/Python_lessons_basic | /lesson01/home_work/hw01_easy.py | 2,087 | 3.53125 | 4 |
__author__ = 'Долгодворов Андрей Игоревич'
# Задача-1: Дано произвольное целое число (число заранее неизвестно).
# Вывести поочередно цифры исходного числа (порядок вывода цифр неважен).
# Подсказки:
# * постарайтесь решить задачу с применением арифметики и цикла while;
# * при желании решите задачу с применением цик... |
bda09e5ff5b572b11fb889b929daddb9f4e53bb9 | rhps/py-learn | /Tut1-Intro-HelloWorld-BasicIO/py-greeting.py | 318 | 4.25 | 4 | #Let's import the sys module which will provide us with a way to read lines from STDIN
import sys
print "Hi, what's your name?" #Ask the user what's his/her name
#name = sys.stdin.readline() #Read a line from STDIN
name = raw_input()
print "Hello " + name.rstrip() #Strip the new line off from the end of the string
|
795d075e858e3f3913f9fc1fd0cb424dcaafe504 | rhps/py-learn | /Tut4-DataStructStrListTuples/py-lists.py | 1,813 | 4.625 | 5 | # Demonstrating Lists in Python
# Lists are dynamically sized arrays. They are fairly general and can contain any linear sequence of Python objects: functions, strings, integers, floats, objects and also, other lists. It is not necessary that all objects in the list need to be of the same type. You can have a list wit... |
f84081ec546e1f88ddb55bfce4e3f114df2c3966 | rhps/py-learn | /Tut5-BasicControl/py-ifelse.py | 124 | 3.734375 | 4 | x = int(raw_input())
if x < 10:
print 'one digit number'
elif x < 100:
print 'two digit number'
else:
print 'big number' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.