blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
4cc114a55d3d1a2960f70b6cda136f97acaa4b2f | rogesson/hacker_rank | /python/find_second_maximum_number_in_a_list.py | 323 | 3.890625 | 4 | """ find the runing-up """
def find_score(runners):
""" find runner in a list """
runners = list(set(runners))
runners.sort()
if len(runners) == 1:
return runners[0]
return runners[-2]
print find_score([2, 3, 6, 6, 5]) # 5
print find_score([1]) # 1
print find_score([57, 57, -57, 57])# -... |
6250e424492cf983ef297eeb462aa42a8df96bf8 | jsearfoo/beginner-project-solutions | /Mean_Median_Mode.py | 1,109 | 4 | 4 |
def mean(list):
sum=0
for item in list:
sum += item
mean=sum/len(list)
return mean
def median(list):
sortedlist=sorted(list)
print("Sorted list = \n", sortedlist)
mid=int(len(list)/2)
return list[mid]
def mode(list):
sortedlist=sorted(list)
mo... |
00037278c97964573ac74535f6761450b5e1216b | Manpreet1398/Mr.Perfecto | /widget_fitting_layout.py | 425 | 4.5625 | 5 |
from tkinter import *
root=Tk()
one=Label(root,text="One",bg="red",fg="white")
one.pack()
two=Label(root,text="Two",bg="green",fg="black")
# this will fill the complete widget as wide
# as parent window is
two.pack(fill=X)
#
three=Label(root,text="Three",bg="blue",fg="red")
# # this will fill the comple... |
dbb65b275f54285d8c6d4faa8e0dc1286048d57d | danylo-boiko/HackerRank | /Problem Solving/Basic/counting_sort_2.py | 518 | 3.71875 | 4 | # https://www.hackerrank.com/challenges/countingsort2/problem
# !/bin/python3
def countingSort(arr):
count = [0] * (max(arr) + 1)
for num in arr:
count[num] += 1
sortedArr = []
for i in range(len(count)):
while count[i] != 0:
count[i] -= 1
sortedArr.append(i)
... |
6026f45e501b8b27938addd96fa891dc80a69239 | Gaydarenko/PY-111 | /Tasks/c0_fib.py | 806 | 4.40625 | 4 | def fib_recursive(n: int) -> int:
"""
Calculate n-th number of Fibonacci sequence using recursive algorithm
:param n: number of item
:return: Fibonacci number
"""
# print(n)
if n < 0:
raise ValueError
if n == 0:
return 0
if n == 1:
return 1
return fib_rec... |
2f4ee77b13a7a0c3ed76af0c38fac2aa1d243c22 | Aadesh-Shigavan/Python_Daily_Flash | /Day 4/04-DailyFlash_Solutions/17_Jan_Solutions_Two/Python/program3.py | 607 | 4.09375 | 4 |
def check(age, sex, status) :
if(sex == 'f' or sex == 'F'):
print("She will work in Urban areas")
elif(age >= 20 and age <= 40):
print("He will work in any areas")
else :
print("He will work in urban areas")
print("Enter age, sex(m/f), Marital Status(y/n)")
try:
age = int(raw_input())
sex = raw_input()... |
1955e5c8575eb8f91e0ea435031ac52adc6c9384 | rhitchcock/advent-of-code-2017 | /day11/part2.py | 609 | 3.6875 | 4 | #!/usr/bin/env python3
import math
def main():
with open("input.txt") as f:
directions = f.read().strip().split(",")
n = 0
ne = 0
nw = 0
furthest_distance = 0
for direction in directions:
if direction == "s":
n -= 1
elif direction == "n":
n += 1
elif direction == "ne":
ne... |
4e290482725a4cbaec8f6885f25a6dd27d1628d7 | Nitheesh1305/Innomatics_Internship_APR_21 | /Task - 2 (Python Programming)/15.py | 284 | 3.796875 | 4 | #Question 15- Set .symmetric_difference() Operation
n = int(input())
english_students = set(list(map(int, input().split())))
b = int(input())
french_students = set(list(map(int, input().split())))
print(len(list(english_students.symmetric_difference(french_students)))) |
f295d9b8ce70483792141ce1980493c8e3261adc | deanc474/myrepo | /TrigInterp.py | 1,453 | 3.890625 | 4 | import numpy as np
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
def TrigInterp(x,y,Nnew):
#Trigonometric Interpolation
#Input
#x = Interpolation nodes (vector of length N)
#y = Interpolation nodes (Vector of length N)
#Nnew = New... |
e8ba8723a08a2140b8ee4232606f10e07997528c | karolinanikolova/SoftUni-Software-Engineering | /2-Python-Fundamentals (Jan 2021)/Course-Exercises-and-Exams/00-Exam-Prep/01_Mid_Exam_Prep/05-Programming-Fundamentals-Mid-Exam/02-MuOnline.py | 2,429 | 3.78125 | 4 | # Problem 2. Mu Online
# You have initial health 100 and initial bitcoins 0. You will be given a string, representing the dungeons rooms.
# Each room is separated with '|' (vertical bar): "room1|room2|room3…"
# Each room contains a command and a number, separated by space. The command can be:
# • "potion"
# o You are h... |
1531e31e18e4b827a4e35fb91427f9da7fd9af20 | rafamancan/python_estudo | /aulas/app2/descontos.py | 865 | 3.515625 | 4 | # -*- coding: UTF-8 -*-
# descontos.py
class Desconto_por_cinco_intens(object):
def __init__(self):
self._proximo_desconto = None
def adicionar_proximo_desconto(self, proximo_desconto):
self.__proximo_desconto = proximo_desconto
def calcular(orcamento):
if(orcamento.total_itens > 5):
retur... |
7ad2a7cf4a696e6dac117f531ba933693fe27b13 | JeremyBakker/Scala-PySpark-and-Spark | /pyspark.py | 11,813 | 3.765625 | 4 | # Create RDD
lines = sc.textFile("README.md")
# Basic Filter with lambda
pythonLines = lines.filter(lambda line: "Python in line")
# Basic Count
pythonLines.count()
# Pull the first line
pythonLines.first()
# Persist an RDD in memory -- useful when needing to use an intermediate RDD
# multiple times
pythonLines.per... |
16c7ce1f668ee538c4ef72a6ca64894aec0a4186 | fightpf/pythontest | /pythonclass/Fibonacci.py | 289 | 4.03125 | 4 | def Fibonacci(n):
if n==1:
return 1
if n==2:
return 1
return Fibonacci(n-1)+Fibonacci(n-2)
print(Fibonacci(10))
def Fibonacci2(n):
a,b=1,1
answer=a
for i in range(n-2):
answer=a+b
a,b=b,answer
return answer
print(Fibonacci2(10)) |
0463d59a9d30958f8fb3ad9f1769d7c292cfe5fe | gschen/sctu-ds-2020 | /1906101004-唐娜/day0226/作业5.py | 401 | 3.671875 | 4 | #5. (使用循环和判断)输入三个整数x,y,z,请把这三个数由小到大输出。
x = input('请输入第一个整数:')
y = input('请输入第二个整数:')
z = input('请输入第三个整数:')
arr = [x,y,z]
for i in range(0,3):
for j in range(i,3):
if int(arr[i])>int(arr[j]):
k = arr[i]
arr[i] = arr[j]
arr[j] = k
print(arr) |
4a6369af1278af85c1ac5d650c716c283898da32 | swapnil2188/python-myrepo | /tests/practice/age_name.py | 214 | 3.8125 | 4 | #!/usr/bin/python
name = raw_input("Your name please: ")
print name
age = raw_input("Enter your age: ")
age = int(age)
print age
s = (100 - age)
r = (s + 2019)
print name ,"will be 100 years old in the year", r
|
510c69d30b33403c2c105c00078532184f9a1dd1 | Thotasivaparvathi/siva | /program31.py | 96 | 3.90625 | 4 | string=input()
char=0
word=0
for i in string:
char+=1
if i==' ':
word+=1
print(char-word)
|
bc69a4b5619da70de1d8f5367151d1f6003b7046 | jpro6679/kopo_univ | /test.py | 340 | 3.59375 | 4 | import math
th = math.radians(1) # 각도 10도를 라디안으로 변환하여 th 에 대입
print("θ =", th, "rad =", math.degrees(th), "°\n") # 라디안과 각도 출력
print( "sin =", math.sin(th)) # 사인 (Sine)
print( "cos =", math.cos(th)) # 코사인(Cosine)
print ("tan =", math.tan(th) ) # 탄젠트(Tangent)
|
3b35d6e92bd215c4a43428ae7ad5020e32ed6d7a | swagMASTER99swag/ComputationalThinking | /CaeserCypher.py | 566 | 3.90625 | 4 |
message = input('message: ')
key = 13
mode = 'decrypt'
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
translated = ''
message = message.upper()
for symbol in message:
if symbol in LETTERS:
num = LETTERS.find(symbol)
if mode == 'encrypt':
num = num + key
elif mode == 'decrypt':
... |
62ad0cdecbb43d25fbae24b2514210a2cd9e56dc | amarjeet-kaloty/Data-Structures-in-Python | /linkedList.py | 1,320 | 4.125 | 4 | class node:
def __init__(self, data=None):
self.data=data
self.next=None
class linkedList:
def __init__(self):
self.head = node()
#Insert new node in the Linked-List
def append(self, data):
new_node = node(data)
cur_node = self.head
while (c... |
a8037f60d639438806c963aa08f69effae8a4e5a | VeigerBroth/xo_game | /xo.py | 4,095 | 3.703125 | 4 | import os
from random import randint
from time import sleep
def checker():
### check if X has winning combination
if (
field[0]==x and field[1]==x and field[2]==x
or field[3]==x and field[4]==x and field[5]==x
or field[6]==x and field[7]==x and field[8]==x
or field[0]==x and f... |
5326d72c3c6b7a3109cd5b8e4672c73fa372d094 | JacobLiebenow/Waves-In-Motion | /datacls/organization.py | 1,487 | 3.671875 | 4 | #Written by: Jacob S Liebenow
#
#
#
#A organization is a conglomerate of contacts, each with their own associated role (which might or might not be
#specified). Bands are scheduled to play at various venues during certain days. They might also frequent
#venues, and be worked with promoters.
from datacls import conta... |
ca15d5eaf0a18e35c51bff75c1e474e293f108f4 | gladius99/Destroy_the_Kilge | /kilge/main2.py | 17,893 | 3.890625 | 4 | #program goes here from main.py then from here goes to "program start"
def start_point():
print "you enter the bunker, wandering what will happen..."
import main as a
import time
time.sleep(1)
a.checkpoint = 1
first_room()
#location functions
def first_room():
import main as a
print "this is the bunker entranc... |
ce7f989222dfefda911392e7e8341e62f558c210 | Yasaman1997/My_Python_Training | /Practice/Practice/Tic Tac Toe/draw/+_Check.py | 3,416 | 4.15625 | 4 | # Python Exercises http://www.practicepython.org/
# Exercise 27 - Tic Tac Toe Draw
# Exercise to draw Tic Tac Toe gameboard the game board getting input from Player 1 and Player 2
# Last updated: 17/02/2016
#
# - gets input from two players
# - checks the input for correctness: row,col
# - exits if board is full or the... |
967f803d07edc5714f0f8a4d85b546947370252f | zacharyDWelch/Electrodynamics | /Drawing copy.py | 5,049 | 4.09375 | 4 | from tkinter import *
import math as m
"""
*************** Things to think about *************************
At some point get the circle to be randomly be placed in the grid.
TODO:
"""
class Drawing:
def __init__(self):
self.master = Tk()
self.master.title("Drawing of Circle and Charge Points"... |
0f12223e1f3599189b541cb720a731e0695bcdf0 | Birtab18/Verkefni | /verk6/verk6.2.py | 99 | 3.8125 | 4 | s = input("Input a string: ")
first_three = (s[0:3])
s = (s[3:])
s = s + first_three
print(s) |
86ebf80f6b0e59b0247f670926efdd884b9eadfa | anilgeorge04/learn-ds | /datacamp/containers/namedtuple.py | 778 | 3.84375 | 4 | # Import namedtuple from collections
from collections import namedtuple
# Create the namedtuple: DateDetails
DateDetails = namedtuple('DateDetails', ['date', 'stop', 'riders'])
# Create the empty list: labeled_entries
labeled_entries = []
# Iterate over the entries list
for date, stop, riders in entries:
# Appen... |
373ec2563a9df9ac68f46044667f82c6f3c14d8b | macantivbl/Python | /Ejemplos/iterables_diccionarios.py | 199 | 3.84375 | 4 | user = {
'nombre': 'Golem',
'edad': 27,
'puede_nadar': False
}
for key, value in user.items():
print(key, value)
for item in user.values():
print(item)
for item in user.keys():
print(item)
|
4352569de062e47860b58b00eabc74fa9c280513 | nurshahjalal/python_exercise | /lambda_map_filter_reduce/lambda.py | 549 | 4.125 | 4 | # A lambda_map_filter_reduce function is a small anonymous function.
# A lambda_map_filter_reduce function can take any number of arguments, but can only have one expression.
# The expression is evaluated and returned. Lambda functions can be used wherever function objects are required.
#regular function
def double(... |
f4be2e488fbc8b9d06320c5dd70e9be8e30518d9 | nilearn/nilearn | /examples/02_decoding/plot_haxby_glm_decoding.py | 5,979 | 3.84375 | 4 | """
Decoding of a dataset after GLM fit for signal extraction
=========================================================
Full step-by-step example of fitting a GLM to perform a decoding experiment.
We use the data from one subject of the Haxby dataset.
More specifically:
1. Download the Haxby dataset.
2. Extract the ... |
4092b891485ab6ce925c4e39d608da427af9c159 | lilyandcy/python3 | /leetcode/removeNthFromEnd.py | 586 | 3.71875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
cur = head
ar... |
76c478bd69b0bf29184502df171c59e51288bc09 | DigitalSlideArchive/HistomicsTK | /histomicstk/segmentation/rag_color.py | 2,295 | 3.546875 | 4 | import numpy as np
def rag_color(adj_mat):
"""Generates a coloring of an adjacency graph using the sequential coloring
algorithm. Used to bin regions from a label image into a small number of
independent groups that can be processed separately with algorithms like
multi-label graph cuts or individual ... |
01b3414b0422ed14788d7f1b4eea211b6f397c2a | vinay01joshi/python-learning | /PlayGround/DataStructure/arrays.py | 129 | 3.515625 | 4 | from array import array
numbers = array("i", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
numbers.append(44)
numbers[0] = 1.0
print(numbers)
|
87b409b429e0201b90cef0e38a1b1017cfe94431 | aabhishek-chaurasia-au17/MyCoding_Challenge | /coding-challenges/week15/day05/Q.1.py | 1,542 | 3.578125 | 4 |
"""
Q-1 ) Gas station (Google interview problem)
https://leetcode.com/problems/gas-station/
(5 marks)
(Medium)
There are n gas stations along a circular route, where the amount of gas at the
ith station is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from
the ith station to i... |
5b5ea808baf9b8dd0661370b9afe577969fdc31f | vigneshpr/sample | /single_list.py | 2,902 | 3.765625 | 4 | '''Here I make use of LIST for implementation.Here the address be the index values and the value be the actual data'''
import time
base_ls=[1,2,3,4,5,6]
def dis():
if(len(base_ls)==0):
print("Empty Linked_list")
proceed()
else:
print("Display Linked_list")
for i in range(len(base_ls)):
print("Key-->",i,"... |
029c30b9757f8fe26e606746e4bed4e37fe1775e | MickRoche/Data-Processing | /Homework/Scraping/tvscraper.py | 3,942 | 3.828125 | 4 | #!/usr/bin/env python
# Name: Mick Roché
# Student number: 10739416
"""
This script scrapes IMDB and outputs a CSV file with highest rated tv series.
"""
import csv
from requests import get
from requests.exceptions import RequestException
from contextlib import closing
from bs4 import BeautifulSoup
from urllib.request... |
84c04e89ce8de7303630243259dcb4cb3d16e0b5 | LMaunish23/Rock-Paper-Scissor-Lizard-Spock | /rpsls.py | 3,365 | 4.21875 | 4 | #A game on Rock Paper Scissors Lizard Spock (by Sam Kass and Karen Bryla) which was featured
#in The Big Bang Theory. Here the game-play is against Sheldon (the characeter from
#The Big Bang Theory). Good Luck playing against him!
#!/usr/bin/python -tt
"""Keywords are used instead of whole Name of elements, so that ... |
fc69197a1680a9678f113fda8f32615ad9d50e64 | bharathtintitn/HackerRankProblems | /HackerRankProblems/soduko.py | 2,494 | 3.703125 | 4 | import pdb
class Solution(object):
def isValidSudoku(self, board):
self.board = board
self.queue = []
self.getAllIndex()
self.numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
print "Final:", self.board
return self.gosudoku(0)
def getAllIndex(self):
... |
0bf7565b6aa7c5d64a490da5742b798b3b3b2f9b | vishrutkmr7/DailyPracticeProblemsDIP | /2022/12 December/db12042022.py | 816 | 4.09375 | 4 | """
Given a string, s, that represents a Roman numeral, return its associated integer value.
Note: You may assume that each string represents a valid Roman numeral and its value will
not exceed one thousand.
Ex: Given the following string s...
s = "DCLII", return 652.
Ex: Given the following string s...
s = "VIII", r... |
31df1e543fc7506322c31412765b39a9761fc72f | CelsoUliana/Introduction-to-Algorithms | /2/2.1 Insertion Sort/2.1-4.py | 531 | 3.625 | 4 | # Celso Uliana -- Jan 2021
# Linear binary array add python 3
A = [1, 1, 1, 1, 0, 0] # 60
B = [1, 0, 1, 0, 0, 1] # 41
def binaryAdd(A, B):
# Initialize n + 1 bit array
C = [0 for i in range(len(A) + 1)]
carryOver = 0
# Reverse iterate it with carry over
for i in reversed(range(len(A) + 1)):
... |
d7e0f1163860935b988ea45cae130300a471dd18 | maodunzhe/clean_code | /backtracking/N-Queens.py | 914 | 3.5625 | 4 | '''
if wanna change certain character in string:
1st way:
test = 'abcd'
new = list(test)
new[2] = 'Q'
''.join(new)
2rd way:
test = 'abc'
test = test[:2] + 'Q' + test[3:]
'''
class Solution(object):
def solveNQueens(self, n):
res = []
options = []
for i in range(n): ## string is not mutable in python
string... |
664586415b303d5dd3daac7cfed1f59e84792499 | Judice/iterator_nest | /Fibonacci.py | 1,343 | 3.578125 | 4 | # coding=utf-8
"""
斐波那契数列
"""
#for循环生成斐波那契数列
def fibs(n):
a, b = 0, 1
for i in range(0,n):
f = a
a, b =b, a+b
print f
#递归函数生成斐波那契数列
def fibs(n):
if n < 2:
return n
else:
return(fibs(n-1) + fibs(n-2))
def run(items):
for i in range(items):
print(fibs(i)) ... |
9b78b5c4879e276aafcbfc47cfc9539a6757fcf4 | hiroaki-yamamoto/tensorflow-demo | /mnist_keras.py | 3,170 | 3.546875 | 4 | #!/usr/bin/env python
# coding=utf-8
"""Mnist CNN based on keras' example."""
from keras.datasets import mnist as input_data
from keras import backend as K
from keras.models import Sequential
from keras.layers import (
Dense, Dropout, Activation, Flatten, Convolution2D, MaxPooling2D
)
from keras.utils import np_u... |
4ce5d23ec1bebd5ec3f89ce336d6b9405c8205fd | LoftyCloud/py_games | /snack/snake01.py | 1,460 | 3.765625 | 4 | import tkinter as tk
R = 50
C = 50
cell_size = 10
win = tk.Tk()
canvas = tk.Canvas(win, width=C * cell_size, height=R * cell_size)
snack_list = [(0, 0), (1, 0), (2, 0)]
snack_color = "green"
food_color = "red"
def draw_single_cell(canvas, c, r, color="black"):
"""
draw black cell with white edge
:param ... |
e763b24ccea8962a80ebd5ba41fa72a4b297c7fd | Stepancherro/Algorithm | /two_array_median.py | 817 | 3.75 | 4 | # -*- encoding: utf-8 -*-
import math
# 中位数索引
def median_index(n):
if n % 2: # 奇数情况
return n // 2
else: # 偶数情况
return n // 2 - 1
def two_array_median(X, Y):
n = len(X)
if n == 1: # 如果数组只有一个元素,则取两者最小的为中位数
return min(X[0], Y[0])
m = median_index(n) # 计算每个数组的中位数索引
i... |
2a739fd5741ada08166eb9761dc0983c80a16b45 | Jeroen-dH/collections | /mm.py | 300 | 3.75 | 4 | # print(random.randint(3, 9))
import random
kleuren = ['oranje', 'blauw', 'groen', 'bruin']
global aantal
aantal = input("hoeveel m&m's wil je: ")
def zakie(aantal):
zak = []
for a in range(int(aantal)):
zak.append(random.choice(kleuren))
return zak
print(sorted(zakie(aantal))) |
b87dc73d86d909ff2dde32912fb8d7fa90d3ad3c | tuseto/PythonHomework | /week6/1-List-Functions/list_functions.py | 915 | 3.5 | 4 | def head(arr):
return(arr[0])
def last(arr):
return(arr[len(arr)-1])
def tail(arr):
new_arr = []
for i in range(1,len(arr)):
new_arr += [arr[i]]
return(new_arr)
def equal_lists(arr1,arr2):
if len(arr1) == len(arr2):
for i in range(0,len(arr1)):
if arr1[i] != arr2[i... |
f70a0260743e6483810ec3aa7e02b445285678c2 | bouxtehouve/iTarot | /paquet.py | 2,107 | 3.609375 | 4 | # gestion du paquet en terme de regles du jeu (et pas de donne)
import random,copy
# Cette classe permet de creer un paquet de cartes melangees aleatoirement et de distribuer les cartes aux joueurs.
from cartes import carte
class paquet: # faire ici la comparaison ?? car la creation des cartes se fait ici
def __ini... |
8c9df66bf6f6d7cb7125ca18b38d38c59c41c952 | fndhnf/gaih-students-repo-example | /Homeworks/HW1.py | 701 | 3.953125 | 4 | #Explain your work
#####
nums = list(range(100)) #a=100 dersek
evenlist = []
oddlist = []
# odds = [i for i in numbers if i%2!=0] alternatif olabilirdi
for x in nums: # bu formatta istendigini dusundugumden, buradan devam ediyorum
if (x % 2 == 0) : #2ye kalansız bolunuyorsa cıfttir
evenlist.append(x)
if (x... |
6fc368947b70134a612c6fb986d8cf4800d91344 | japark/PythonWebScraper | /Basics/basics_for_beginners.py | 1,697 | 3.609375 | 4 | from urllib.request import urlopen
from urllib.error import HTTPError, URLError
from bs4 import BeautifulSoup
'''
*** NOTE ***
1) urlopen 함수
ㄴ GET 요청으로 https://www.example.com 의 HTML 코드 가져오기
2) BeautifulSoup 객체
ㄴ BeautifulSoup 객체에서 특정 태그를 골라내기
3) 예외처리 1
ㄴ 페이지를 찾을 수 없거나 URL 해석에서 에러가 생긴 경우 : HTTPError
ㄴ 서... |
6864cffb99ff8010774fc0d34193798cebcd5a22 | candyer/leetcode | /hIndex.py | 1,471 | 4.15625 | 4 | # https://leetcode.com/problems/h-index/description/
# 274. H-Index
# Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.
# According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers ... |
44e7abfb1ee7bba5bc0725ea222bc2b3e815902a | AlifsyahRS/Alif-PythonExercises | /dictionary-review/dict_exercise1.py | 244 | 4.09375 | 4 | # Dictionary Exercises Question 1
input_dict = {'hello': 1, 'a': 2, 'world': 'lol'}
def removekeys(mydict, keylist):
for keyword in keylist:
del (mydict[keyword])
return mydict
print(removekeys(input_dict, ['hello', 'a']))
|
d40382f1fabfee8a0dde52a4b3b61d7b4c4d475b | DahrielG/tuitionPreparation | /app/models/model.py | 661 | 3.671875 | 4 | # weeks = (years * 52) + (months * 4)
def weeksLeft(gYear, gMonth, cYear, cMonth):
years = int(gYear) - int(cYear)
months = int(gMonth) - int(cMonth)
weeks = (years * 52) + (months * 4)
print(weeks)
return weeks
# weeksLeft()
def equation(weeksAmount, tuition):
weekly = int(tuition) / int... |
fe26eb9ae8b9f78920450f84e39182c632970f41 | djwen0726/python3-tutorials | /生产者消费者练习1.py | 1,265 | 3.96875 | 4 | import queue
import random, threading, time
# 生产者类
class Producer(threading.Thread):
def __init__(self, name, queue):
threading.Thread.__init__(self, name=name)
self.data = queue
def run(self):
for i in range(10):
data=random.randint(0,100)
print("%s i... |
4964769a43a9d98b9b98cc363c1bd187b1587edd | MohammedHassan25/Programming-Foundations-Fundamentals | /chap 05/01_Introduction to functions.py | 886 | 3.953125 | 4 | # -------------------------------------------------------------------------------------
# Function : Block of code packaged together with a name ( ex : print(), input() )
# "def" shortens you many steps and lines
# -------------------------------------------------------------------------------------
# for example
pri... |
2883cab45c71d7b3cbcdf254f7b13f0a93302c69 | KathrynMorgan/sort | /Python3/Studying/Lesson_1/alphabet_and_numbers.py | 982 | 4.0625 | 4 | #!/usr/bin/env python3
# Make a variable into a multi line string; where does this variable get used?
first = ''' Tell me the alphabet!
Please please please?
What are the first 4?
'''
second = '''
But wait, that looks funny!\n\
Can we put them in order?\n\
'''
# We are going to count and play with the alphabet!
p... |
db1a3143c2cbf6240d2a521430b1cadd693f67cf | frobes/python_learning | /.idea/jichu/names_list.py | 103 | 3.640625 | 4 | #coding=utf-8
names = ['pow','aaab','keh','jack','bob']
for name in names:
print name.title()
|
b055b74ada29a22e192b2c797d717e48c102bac0 | cgordoncarroll/dailyProgrammer | /Easy/148/combinationLock.py | 750 | 3.703125 | 4 | #!/usr/bin/python
import sys
def main(argv):
dialSize = int(argv[0])
firstNum = int(argv[1])
secondNum = int(argv[2])
thirdNum = int(argv[3])
totalIncrements = 0
totalIncrements += dialSize*2 #First two full turns
totalIncrements += firstNum #Turn to first num
#Determine distance for turn 2
secondTurn = (d... |
a63fd46f15494b33e7f4587f2780155ec511c264 | qmnguyenw/python_py4e | /geeksforgeeks/python/python_all/158_16.py | 2,029 | 4.46875 | 4 | Python | Filter the negative values from given dictionary
Given a dictionary, the task is to filter all the negative values from given
dictionary. Let’s discuss few methods to do this task.
**Method #1: Using dict comprehension**
__
__
__
__
__
__
__
# Python code to demonstra... |
e5021fe57391bf5c88313fff80fcf5f8dee7d0aa | golz04/py-cli-basic | /soal3.py | 450 | 3.90625 | 4 | try :
x = int(input("Masukkan Angka Pertama :"))
y = int(input("Masukkan Angka Kedua :"))
if (x == y) :
if (x%2 == 0) :
print("Hasilnya 0")
elif (x%2 == 1) :
print("Hasilnya 1")
elif (x%2==0 and y%2==1) :
hasil = (x*y)+y
print("Hasilnya",hasil)
... |
8bb8e72518d7fe554d5412507845719ccaca361c | btrif/Python_dev_repo | /Algorithms/Trees & Search Trees/Binary Search Tree 5.py | 4,515 | 4.125 | 4 | # Created by Bogdan Trif on 15-05-2018 , 5:26 PM.
# https://stackoverflow.com/questions/2598437/how-to-implement-a-binary-tree?answertab=votes#tab-top
# Here is my simple recursive implementation of binary tree.
class Node:
def __init__(self, val):
self.l = None
self.r = None
self.v = val... |
398929f2a1338cf85a2aa5466c127b236330e9ca | wwylele/chocopy-rs | /chocopy-rs/test/pa2/bad_semantic.py | 686 | 3.65625 | 4 | # Please also refer to other files in student_contributed for more tests
x:int = 1
x:int = 2 # global name collision
class u(y): # define u before y
pass
class y(object):
z: int = 0
def z(self: y): # member name collision
pass
def bar(): # missing self
pass
def foo(self: y, y: int... |
f378ad515abc05ce67ff75a0b024ec26e995bc07 | ubercareerprep2021/Uber-Career-Prep-Homework-Gabriel-Silva | /Assignment-3/sorting_algorithms/quick_sort.py | 1,074 | 4.03125 | 4 | def quick_sort(array: list, low: int, high: int):
if len(array) == 1:
return array
if low < high:
# index of smaller element
partition_index = (low-1)
# pivot element as the highest index
pivot = array[high]
# places smaller than pivot elements to the left and
... |
3840d2a3ad4149dc484ad9ebfeaa4f1fa4b1ae54 | jtarlecki/project_euler | /p17.py | 1,938 | 3.53125 | 4 | class NumberToString(object):
ones = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
teens = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
tens = ['','','twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'e... |
13ad969a12f5844e252d40849b86bf9f79c557f8 | jjohn342/GirlsWhoCode | /pseudo.py | 206 | 4.03125 | 4 | ages = [5, 12, 3, 56, 24, 78, 1, 15, 44]
# find the sum of list
sum = 0
sum = sum(ages)
# find the length
length = len(ages)
average = length / sum
# divide length by sum
print(average)
#print the average
|
6d8b616ee1879ce062a2e7ec8de149fc4f193939 | tacheshun/p1_movie_trailer_website | /entertainment_center.py | 993 | 3.546875 | 4 | import media
import fresh_tomatoes
#create the objects intantiating the Movie Class. Each object must have the movie title for better reading
training_day = media.Movie('Training Day', '2001', 'The story of an undercover police', 'http://upload.wikimedia.org/wikipedia/en/b/b3/Training_Day_Poster.jpg','https://www.yout... |
17b24f580b3f343d3d618ea601f36e4359402d66 | qvpiotr/ASD | /Graphs/Bellman-Ford.py | 1,190 | 3.53125 | 4 | #algorytm Bellmana-Forda
class vertex:
def __init__(self):
self.visited = False
self.parent = None
self.d = float("inf")
def neighbour(G,s):
neigh = []
for i in range (len(G)):
if G[s][i]!=0:
neigh.append(i)
return neigh
def bellman(G,s):
... |
870ec6a8d13a5a56559a1b5abbec1802d11465bf | tearuka/AoC_2020 | /Day09.py | 1,055 | 3.5625 | 4 | #!/usr/bin/env python
# coding: utf-8
# read input
inp = open("inp/input_09.txt").read().splitlines()
inp = [int(line) for line in inp]
### Part 1
def is_sum(data, objective, preamble):
counter = 0
for num in data:
difference = objective - num
if difference not in data:
counter ... |
65d53a514aecfe0d445e3097fec9a2e32b0f2674 | beringresearch/ivis | /ivis/data/generators/triplet_generators.py | 8,289 | 3.5625 | 4 | """
Triplet generators.
Functions for creating generators that will yield batches of triplets.
Triplets will be created using neighbour matrices, which can either be precomputed or
dynamically generated.
"""
from abc import ABC, abstractmethod
from functools import partial
import itertools
import random
import math
... |
e1b67114daa05030b748cae45b1997f4fca45331 | nealstewart/booth | /symbols/drawing.py | 619 | 3.609375 | 4 | "Drawing logic for symbols"
from symbols import shapes
from symbols import utils
def draw_line(ctx, line):
first_point = utils.get_center(line[0])
second_point = utils.get_center(line[1])
ctx.move_to(first_point[0], first_point[1])
ctx.line_to(second_point[0], second_point[1])
ctx.close_path()
... |
1744d184671c0cb3a39a8496c077c0ec7448aca1 | jorchard/AutoDiff | /utils.py | 3,989 | 3.609375 | 4 | # utils
import numpy as np
import matplotlib.pyplot as plt
# Abstract class
class MyDataset():
def __init__(self):
return
def __len__(self):
raise NotImplementedError
def __getitem__(self):
raise NotImplementedError
# MyDataLoader
class MyDataLoader():
def __init__(self, ds... |
59453ab002f092f5b2c3dcd1bbe545260ddcf7ca | gerardomunoz1/gmunoz_repoSoluciones | /LAB 2.1/lab.py | 1,748 | 3.75 | 4 | M = 1000
D = 500
C = 100
L = 50
X = 10
V = 5
I = 1
def arabigo_a_romano ():
try:
numero_ingresado=int(input("Ingrese un número para su conversión a números Romanos: "))
print ("El número ingresado fue: ", numero_ingresado)
while (numero_ingresado > 3999):
print ("Número ingres... |
ebefea30edf3a0367779d9a243eed3901f007162 | Eric-Wonbin-Sang/CS110Manager | /2020F_hw6_submissions/jaineshita/EshitaJainCH7P2.py | 857 | 4.375 | 4 | # I pledge my Honor that I have
# abided by the Stevens Honor System.
# Eshita Jain
# program determines date validity
def main():
isValid = True
months_with_31_days = [1, 3, 5, 7, 8, 10, 12]
date = input("Enter date (mm/dd/yyy): ")
date_list = date.split("/")
if len(date_list) != 3:
isVal... |
65b88ff3d4a6b254b46f8dfa86e1c1850974a00d | royhuang813/shiyanlou-python | /challenge-1/calculator.py | 724 | 3.65625 | 4 | #!/usr/bin/env python3
def f(x):
b = x - 3500
if b <= 0:
print(format(0,'.2f'))
elif 0 < b <= 1500:
print(format(b * 0.03 - 0, '.2f'))
elif 1500 < b <= 4500:
print(format(b * 0.1 - 105, '.2f'))
elif 4500 < b <= 9000:
print(format(b * 0.2 - 555, '.2f'))
elif 9000 <... |
fd4fba0fe69b0e1195d19b221dcee0a94331e1f6 | gcspanda/Python-Crash-Course | /ch05/5-09.py | 160 | 3.8125 | 4 | names = ['admin', 'panda', 'tiger', 'dog', 'cat']
# names = []
if names:
for name in names:
del name
else:
print("We need to find some users.") |
b7dedd7263d4fe2a1b0ccc918258bd33cf64cd79 | jun-young000/grammar-basic | /variale/02_variable1.py | 981 | 3.71875 | 4 | # 변수는 할당해놓고 사용하지 않으면 메모리 공간을 차지하게 됨
# 변수 삭제 명령어 : del
# del 변수명
# c_var = 100
# print(c_var)
# del c_var
# print(c_var)
# 문자열 값 저장
# 문자열을 큰따옴표 사용 (작은따옴표도 사용가능)
# 여러 종류의 따옴표를 사용시에는 짝을 맞춰야 함
name = "홍길동"
std_name = '김철수'
pro_name = "이몽룡'교수'"
print(name)
print(std_name)
print(pro_name)
address ='서울시 강남구'
print(name... |
d572b47a3f16e2b55b5efa2f222188c8860d08f2 | whyismefly/learn-python | /xiaojiayu/P17-20.py | 689 | 3.75 | 4 | #!/usr/bin/python
# encoding:utf-8
a=list()
print a
b="fwhfjerqwofk'erkfpoerw"
b=list(b)
print b
print len(b)
print max(b)
b.append(1)
print b
print min(b)
print sorted(b)
print list(reversed(sorted(b)))
def function1(a,b):
"dfwifuoheroigioer"
return a+b
print function1(3,5)
print function1.__doc__#打印方法注释
def ... |
4d245b29fc2d55e368ef053a16342e9aececb3cf | ellelater/Baruch-PreMFE-Python | /level5/5.1/5.1.4.py | 745 | 3.671875 | 4 | import datetime
def main():
date = raw_input("Input date (in format %Y-%m-%d):")
time = raw_input("Input time (in format %H:%M:%S):")
t = datetime.datetime.strptime(date + ' ' + time, "%Y-%m-%d %H:%M:%S")
delta = raw_input("Input delta time: (in format %H:%M:%S:%f)")
sign = 1
if delta[0] == '-... |
3e7d856e0e0d07306c8342d7c9ab9adad0cb807e | ChuhanXu/LeetCode | /Amazon OA2/Most frequent word.py | 1,362 | 4.25 | 4 |
# Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words.
# It is guaranteed there is at least one word that isn't banned, and that the answer is unique.
#
# Words in the list of banned words are given in lowercase, and free of punctuation. Words in the... |
6d5c8f68a0e25fc1e36d37c6d91d1d9f6b22acfd | AYehia0/codingame | /compete/fastest/shift_index.py | 76 | 3.765625 | 4 | n = int(input())
word = input()
print(word[n%len(word):]+word[:n%len(word)]) |
931bd90faf04a6e094a316b1455538d0c9aab199 | S1LV3RJ1NX/SPOJ250 | /22_STPAR.py | 676 | 3.59375 | 4 | # http://www.algorithmist.com/index.php/SPOJ_STPAR
n = int(input())
while n:
side_street = []
# cars = []
curr_car = 1
flag = True
cars = [int(x) for x in input().split()]
# print(cars)
for i in range(n):
while len(side_street) != 0 and side_street[-1] == curr_car:
c... |
2f50c4cf87e4a04d42d1f78a8c141896931e2930 | Kamal-vsi/30days-Python-Bootcamp | /Day17 challenge.py | 2,754 | 3.609375 | 4 | # Python MYSQL
# Create a connection for DB and print the version using a python program
import mysql.connector
db=mysql.connector.connect(host='localhost', user="root", password="Sairam@123")
print(db)
import sys
cur = db.cursor()
cur.execute("SELECT VERSION()")
data = cur.fetchone()
print("DBMS version :",... |
6952e1592dacf20a159208c85e8a009168aec1eb | iandioch/CPSSD | /ca117/lab1.1/contains_11.py | 744 | 3.84375 | 4 | import sys
def count_letters(s):
ans = {}
for c in s:
if c in ans:
ans[c] += 1
else:
ans[c] = 1
return ans
def main():
first_letters = count_letters(sys.argv[1])
second_letters = count_letters(sys.a... |
d5e8b43372c1aacb6ab729e2d8f600f2ac571900 | bruno-victor32/Curso-de-Python---Mundo-1-Fundamentos | /ex029.py | 287 | 3.796875 | 4 | vel = float(input('Digite a velocidade do veiculo em km/h: '))
if vel > 80:
print('Você foi multado devido a está acima do limite de 80 km/h')
mul = (vel - 80) * 7
print('A multa vai custar R${:.2f}'.format(mul))
else:
print('Você está andando na velocidade correta') |
e79ed2a497f7fb675912175f6a431a3635e6643c | Naman0199/Star-Pattern-Game | /tut29exercise.py | 350 | 4 | 4 | print("Pattern Game")
n = int(input("enter the number of rows for patterns:\n"))
b = bool(int(input("enter 1 for True or 0 for False:\n")))
if b==1:
c = 0
while(c<=n):
print("*"*c)
c = c+1
elif b==0:
c=n
while(c>0):
print("*"*c)
c = c-1
else:
print(... |
ac6357a9793386a0f6f0a2368d81dc9b779ca3ad | boppreh/2048bot | /bot.py | 5,514 | 3.796875 | 4 | import random
class GameOver(Exception):
""" Exception raised when the board has no move lefts. """
class Board(object):
"""
Class for storing, changing and moving the tiles.
Methods that change the board return a new changed copy instead.
Invalid positions return -1.
"""
def __init__(sel... |
6750e8ece14262db0c3a6ac5668d510d52f72bff | Tarrasch/Roy_VnTokenizer | /data/clean_dictionary.py | 328 | 3.84375 | 4 | #!/usr/bin/env python3
import fileinput
import re
word = ''
for line_ in fileinput.input():
line = line_.strip()
if re.search('##', line):
for word_ in line.split(','):
word = word_.strip()
word = re.sub('##', '', word)
word = re.sub(' ', '_', word)
prin... |
d8d8a466014b3524cf89111727be5245022099c7 | pdez90/COVID-19_US_County-level_Summaries | /model/sir_model.py | 2,393 | 3.71875 | 4 | # Lightly modified from from https://scipython.com/book/chapter-8-scipy/additional-examples/the-sir-epidemic-model/
# Goal is to learn the beta and gamma parameters from socio-economic facotrs
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
class SIRmodel():
def __init__(sel... |
e01a5f3e3dee7ef4e9a743e69962a9b0fe3b0f61 | CrimsonVista/Playground3 | /src/playground/common/datastructures/HierarchicalDictionary.py | 4,319 | 4.03125 | 4 | from collections.abc import MutableMapping
class HierarchicalKeyHandler(object):
"""
HierarchicalKeyHandler is an abstract class (interface) with
two methods: split and join. Implementing classes should define
split and join for data such that split(data) produces a list
of parts and join(pa... |
aeb1585762c57281450e6540d70ac68fce955179 | ahmetcanbasaran/MU-CSE-Projects | /8.Semester/CSE4094/Project#1/main.py | 3,911 | 3.546875 | 4 | import os
import re
# To make a node
class TrieNode(object):
# default constructor
def __init__(self, char):
self.char = char
self.children = []
self.is_end_of_word = False # Is it the last character of the word.
self.counter = 1 # How many times this character appeared in the... |
5d89d29900dc3d230718a42b33e9684b51375f7d | OlehPalka/Second_semester_labs | /labwork10/mark.py | 3,820 | 3.8125 | 4 | """
This module contains class which saves data in array
"""
import ctypes
class AngleADT:
"""
Class which creates object (array) which saves angles.
"""
def __init__(self):
self.ascii = {'0': 0.0, '1': 22.5, '2': 45.0, '3': 67.5,
'4': 90.0, '5': 112.5, '6': 135.0, '7': ... |
9abaff7bf5fbb426965e216d4b4a900b898b21c7 | baburajk/python | /practice/listmerge.py | 1,810 | 3.828125 | 4 | #!/usr/local/bin/python3
import argparse
class OrderMerge:
pass
def merge(self,list1,list2):
# Make a list to hold both lists
mergedlistsize = len(list1) + len(list2)
mergedlist = [None] * mergedlistsize
current_index_list1 = 0
... |
97e7fe8883606d285eaa22d0820bfe7b7b7e1f3e | weguri/python | /listas_tipos/list/range_list.py | 254 | 4.09375 | 4 | numeros = list(range(1, 8))
print(numeros)
intervalo_numeros = list(range(2, 20, 2))
print(intervalo_numeros)
#
#
print("""\nExemplo For e Range""")
squares = []
for value in range(12):
squares.append(value ** 2) # Exponenciação
print(squares)
|
111e0f374c1bdc8ada830c7bab7a0e9c1a86faff | johncornflake/dailyinterview | /imported-from-gmail/2019-10-12-invert-a-binary-tree.py | 1,088 | 4.25 | 4 | Hi, here's your problem today. This problem was recently asked by Twitter:
You are given the root of a binary tree. Invert the binary tree in place. That is, all left children should become right children, and all right children should become left children.
Example:
a
/
\
b c
/
\
/
d e f
The inver... |
b77e6f30f24f814014afa696862b5bfd97f3c4c2 | thormeier-fhnw-repos/sna-holaspirit-to-gephi | /src/gephi/write_csv.py | 261 | 3.65625 | 4 | import csv
def write_csv(matrix, file_name):
"""
Writes a given matrix into a CSV file
:param matrix: The matrix to write
:return: None
"""
with open(file_name, "w") as f:
writer = csv.writer(f)
writer.writerows(matrix)
|
259362db353b56b8828171a1d9d1d92f4364905d | generalturok/fill_in_the_blanks | /australia_quiz.py | 3,308 | 4 | 4 | '''A Quiz on How Well You know Australian Culture'''
#opening sentence to explain what the program is and what it is about
print "Play my Australia, fill in the blanks game!"'\n'
#Including 3 levels: easy/medium/hard
easy_question = '''Australia was founded in __1__ by Captain James Cook.
The national emblem of Austral... |
8d1f1516aceaae2eddbe0c4566feceafa5df90ac | jarthurj/ThinkPython | /5-3.py | 280 | 4.0625 | 4 | def check_fermat(a, b, c, n):
if a ** n + b ** n == c ** n and n > 2:
print("holy smokes fermat was wrong")
else:
print('NEIN!')
if __name__ == '__main__':
a = int(input("a?"))
b = int(input("b?"))
c = int(input("c?"))
n = int(input("n?"))
check_fermat(a, b, c, n) |
eb1245cfd4f95f072a979ccd5776d0dd3730acc4 | iveygman/SonnetGen | /wordnode.py | 1,602 | 3.5625 | 4 |
class WordNode(object):
def __init__(self, word):
self.word = word;
self.bWords = dict();
self.fWords = dict();
self.nextWord = '';
def addForward(self, fWord):
if (fWord not in self.fWords.keys()):
self.fWords[fWord] = 1;
else:
self.... |
b507e7c6ce6cb44c967a81331a5d3726a2273e09 | r9y9/nlp100 | /09.py | 464 | 3.953125 | 4 | import numpy as np
def f(s):
words = s.split(" ")
r = []
for word in words:
if len(word) < 3:
r.append(word)
else:
subword = [c for c in word[1:-1]]
np.random.shuffle(subword)
r.append("".join([word[0]] + subword + [word[-1]]))
return " "... |
3a0caf8b57c8261a6dec76d07a6fadf1ec81fc5f | chizhangucb/Python_Material | /cs61a/lectures/Week1/Lec_Week1_1_Extra.py | 1,168 | 4.53125 | 5 | #===== The Non-Pure Print Function =====#
-2
None # a special Python value that represents nothing
print(None)
print(None, None)
print(1, 2, 3)
## 1. Pure function:
# Functions have some input (their arguments) and
# return some output (the result of applying them).
abs(-2)
# (1) Pure functions have the property th... |
afa6c9f183f4d9d5c83f9dbf28a63456372eed15 | CSPInstructions/HR-1819-Workshop-Analysis-2 | /Code/Deeltijd.py | 2,696 | 4.21875 | 4 | # Function that prints the contents of a list with their indexes
def printList( list ):
# Print a line
print("------------")
# Create a counter that keeps track of the index
counter = 0
# Loop over the items in the list
for item in list:
# Print the index with it's corresponding value
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.