blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
5b8eb9ff576b910d7bcc5c71e53ca4298d0cc5ac | seobie/algorithms | /가운데글자가져오기.py | 551 | 3.640625 | 4 | """
문제 설명
단어 s의 가운데 글자를 반환하는 함수, solution을 만들어 보세요. 단어의 길이가 짝수라면 가운데 두글자를 반환하면 됩니다.
재한사항
s는 길이가 1 이상, 100이하인 스트링입니다.
"""
def solution(s):
answer = ''
div = int(len(s)/2)
if len(s) % 2 == 0:
answer = s[div-1:div+1]
else:
answer = s[div:div+1]
return answer
# return str[(len(str... |
85efd4a3868608274797daca22b567dc5f63e81d | gittyy1310/guvi-code-kata | /biggest.py | 112 | 3.75 | 4 | n1,n2,n3=input().split()
if(n1>=n2)and(n1>=n3):
print(n1)
elif(n2>=n1)and(n2>=n3):
print(n2)
else:
print(n3)
|
de9a98069631642476e45930c1a493f86e629798 | izzymgm/HODP_Art_Museum | /HAM_API_data_access.py | 1,859 | 3.671875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 2 10:06:57 2020
@author: isabellagm
"""
import requests
import json
def pagination(url):
r = requests.get(url)
# Convert data to jSON format
data = r.json()
# Extract the info and records
info = data['info']
... |
354784d0dc003e64371f25e52084589fb30089e3 | berindererikjanos/Gyakorlo-feladatok-2018-2 | /Anagramma.py | 436 | 3.671875 | 4 | #Kérjen két szót, és írja ki, hogy anagrammák-e.
#Két szó anagramma, ha ugyanazokból a betűkből áll.
def anagramma_e(s1,s2):
s1_rendezve = sorted(s1) #ABC sorrendbe rendezi a betűket, és az eredményt egy új stringbe menti
s2_rendezve = sorted(s2)
if s1_rendezve == s2_rendezve:
return True
else... |
badbad2540eb1fba5c9de66f81fa7674db90d836 | v-shieh/restaurant_rating | /ratings.py | 408 | 3.59375 | 4 | """Restaurant rating lister."""
def get_ratings(filename):
"""Function which opens a .txt file and prints restaurant and corresponding
rating.
"""
ratings = open(filename)
for line in ratings:
rating_list = line.rstrip().split(":")
# print rating_list
restaurant, rating = ... |
0ece865580f259664636f14bfcbabe6ea918fe18 | Johnz86/testbedmonitor | /server/scripts/python/hosts.py | 505 | 3.578125 | 4 | import re
def getEtcHosts():
"""Read the hosts file at the given location and parse the contents"""
with open('/etc/hosts', 'r') as hosts_file:
for line in hosts_file.read().split('\n'):
if len(re.sub('\s*', '', line)) and not line.startswith('#'):
parts = re.split('\s+', li... |
b5ad564f17680e98d3ed7806a9440837f2db34a3 | topliceanu/learn | /python/algo/src/shunting_yard.py | 1,761 | 3.5 | 4 | # -*- coding:utf-8 -*-
from collections import deque
op_prec = {
'+': 2,
'-': 2,
'*': 3,
'/': 3,
'^': 4,
}
def prec(op):
if op in op_prec:
return op_prec[op]
return -1
def assoc(op):
if op == '^':
return 'right'
return 'left'
def shunting_yard(tokens):
output... |
75e2cf0de4c676882a883e8906c7c017205fb364 | Rachanahande/python1 | /LAB_QUESTIONS/interogative.py | 210 | 3.890625 | 4 | while True:
inp = input("enter the string")
if inp == 'done':
break
else:
if inp.endswith('?'):
print("interogative statements")
else:
print("assert") |
9c61957967ca3d8cbd978a02a07c2bc83c3524ec | StaticNoiseLog/python | /ffhs/limes.py | 282 | 3.515625 | 4 | import math
epsilon = 0.0000000001
previous = -1
current = 0
n = 1
#while current - previous > epsilon:
while n < 1009:
previous = current
current = 1/n**3 + math.log10(n)/3628800
# current = math.sqrt(9 + (-1**n/n))
print("n: ", n, " - ", current)
n += 1 |
23f964d6f63804489db206a6b59432bb2e2e9bed | devpaz94/All-Projects | /triangles.py | 1,796 | 3.984375 | 4 | #Take a triangle and select some coordinate inside that triangle and plot a single point. Then randomly pick one of the three
#corners of the triange and plot a new point exactly half way between the point and the corner. From this new point, repeat
#the process picking a corner at random and plotting a point exacl... |
eaab4be803bee8f45472e112ced8336d48146596 | marija2102ua/Homework | /HW7/hw7.1.py | 886 | 4.3125 | 4 | from modules.square_math import rectangle,triangle,circle
def main():
while True:
num = input("""What do you want to calculate?
1.calculates the square of a rectangle
2.calculates the square of triangle
3.calculates the square of circle
Your choice: """)
if num == "1":
sideA = float(in... |
9ac402585c0b139b7a3500e93a5465f7b89cbb97 | dsweed12/My-Projects | /Project II - Python MITx/Midter.py | 1,624 | 3.546875 | 4 | def closest_power(base, num):
guess=0
exp=1
while abs(base**guess - num) != 0:
if num > base**guess:
if abs(base**guess - num) <= abs(base**exp - num):
exp = guess
if base**guess > num:
if abs(base**guess - num) < abs(base**exp - num):
... |
d375793c3358c3260ed9616d2349660fe6b766b4 | EmilyWasher/SomethingAwesome | /python_version/ciphers/rail_fence.py | 2,940 | 4.0625 | 4 | import re
'''
print("Welcome to the rail fence cipher")
# Read in the input, ensuring to sanitise the choice and key
while True:
choice = int(input("Do you want to encrypt (1) or decrypt (2): "))
if choice == 1 or choice == 2:
break
else:
print("Invalid option. PLease select a different opt... |
e16c68ae805ae865fe06ff7cde48e04dd938d889 | rbshadow/Python_URI | /Beginner/URI_1006.py | 288 | 3.546875 | 4 | def math():
a = float(input())
b = float(input())
c = float(input())
update_a = a * 2
update_b = b * 3
update_c = c * 5
result = ((update_a + update_b + update_c) / 10.0).__format__('.1f')
print('MEDIA =', result)
if __name__ == '__main__':
math()
|
15df052ba0344d7ec50beb514711542342b35d4e | RonanAlmeida/income-classifer | /Income Classifer/extractData.py | 3,605 | 3.953125 | 4 | """
This module is used for reading the data and creating the test and training
data sets.
"""
import urllib.request
def readData(url):
"""
This function reads all the data contained in the given url. It creates a dictionary for each line and adds this dictionary to a list.
Parameters:
... |
c1d3205669c264ba7069ca810c2b3bcf45194918 | jancyranij/python | /pg64.py | 143 | 3.734375 | 4 | def sumodd():
a=int(input())
b=int(input())
u=a+b
if u%2==0:
print('even')
else :
print('odd')
try:
sodd()
except:
print('invalid')
|
798028dfc516535c06bcfea95bb337a6eac7d27f | shuiyue-xiaoxiao/xiaomawang_L1 | /小码王-Python-常规课-L1-教学案例-第35课-小码银行3-V3.0-20190920/小码银行(窗口版).py | 5,235 | 3.953125 | 4 | import tkinter # 导入tkinter模块
import tkinter.messagebox # 导入tkinter.messagebox模块
# 账户类
class Account():
def __init__(self, name, password, balance, operation):
self.name = name
self.password = password
self.balance = balance
self.operation = operation
print(self.n... |
97d01ccf479a6e33c4ade4d770066a97a24f8724 | daksh105/CipherSchool | /Assignment4/GenerateValidIp.py | 909 | 3.65625 | 4 | def GenerateValidIp(s):
n = len(s)
if n == 0 or n > 12:
print("NO Valid Ip")
return
total_Ips = []
IpValidChecker(s, total_Ips)
if total_Ips:
for i in total_Ips:
print(i, end = " ")
else:
print("No Valid Ip")
def IpValidChecker(s, total_Ips, current_I... |
f7dedd0f022e0728bcb2a6020785869e3c456adc | snangunuri/python-examples | /readfile.py | 379 | 3.96875 | 4 | #!/usr/bin/python
import sys
input_file= sys.argv[1]
gene= sys.argv[2]
print 'argument is', gene
sequence=""
with open (input_file, 'r') as myfile:
for line in myfile:
if gene in line:
for line in myfile:
if line.startswith('>'):
break
else:
sequence = sequence + line.str... |
4caa864aab4251b5eecbc744da63b5f21d2c110f | MichaelShoemaker/AdventOfCode-2020 | /Day10/Incomplete-Day10-Part2.py | 2,057 | 3.5625 | 4 | #import time
import typing
from itertools import combinations_with_replacement
#Create ordered list of ints, add zero to the beginning
#and a value three larger than the highest value
def make_data(file) -> list:
data = open(file,'r').read().splitlines()
intdata = [int(i) for i in data if len(i) > 0]
intda... |
e3a691a9e5cc437da91cd3904aea3eb1ad25448e | jhn--/sample-python-scripts | /python3/thinkcs-python3/5.14.1.py | 1,483 | 4.3125 | 4 | '''
Assume the days of the week are numbered 0,1,2,3,4,5,6 from Sunday to Saturday. Write a function which is given the day number, and it returns the day name (a string).
'''
#! /usr/bin/env python
def numtoday(num, listofdays):
# print(num)
if num >= 0 and num < 7:
if num == 0:
print(list... |
96dc19a4cdb52380bcb61ad2db12d949b7a2da59 | UpendraDange/JALATechnologiesAssignment | /pythonLoops/program_11.py | 279 | 4.21875 | 4 | """
Program to check whether a number is EVEN or ODD using switch
"""
def demo(arg):
switcher = {
0: "EVEN",
1: "ODD",
}
return switcher.get(arg)
if __name__ == "__main__" :
num = int(input("Enter a number:"))
print("Number is:",demo(num%2)) |
1383f7e4555d702fa1bd0cd6d892f1d980403918 | markleeb/stock_strategies | /trending_value.py | 8,484 | 3.765625 | 4 | import pandas as pd
import numpy as np
import sys
from argparse import ArgumentParser, RawTextHelpFormatter
def read_data(filename, key_file):
"""Reads in filename and assigns column names based on
values in key_file, replacing spaces with '-' in column names.
Returns dataframe.
:filename: data fi... |
b198372f3fb4d338a5771d23748c099261fa89a5 | Bartlomiej9867463/Wizualizacja-danych | /47.py | 1,552 | 3.703125 | 4 | class robot:
# definicja konstruktora
def __init__(self, x, y, krok, xa,ya):
if xa>x or ya>y or xa<1 or ya<1:
print("robocik spadl z planszy :(")
del self
else:
self.x=x
self.xa = xa
self.y = y
self.ya = ya
... |
402bd83fe350343fffc89cb25cb3e58928395bfe | miroslavgasparek/python_intro | /pandas_intro.py | 2,697 | 4.25 | 4 | # 03 March 2018 Miroslav Gasparek
# Python bootcamp, lesson 30: Introduction to Pandas
# Import modules
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
rc={'lines.linewidth': 2, 'axes.labelsize': 18, 'axes.titlesize': 18}
sns.set(rc=rc)
# Read in data files with pandas
df... |
610c4b71682e1b62efdc236f19455fd3ec1d37da | xmu-ggx/coding-in-offer | /2-二叉树/2-1.py | 628 | 3.625 | 4 |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回对应节点TreeNode
def KthNode(self, pRoot, k):
if pRoot is None or k <= 0:
return None
stack = [pRoot]
count = 0
while stack:
... |
004b005d61815271a08b2c7d87cd76563f6cc4f0 | candekn/PythonDia1 | /EjercicioSeis.py | 650 | 3.796875 | 4 | #Tipos de colecciones: Listas, Tuplas y Dicionarios
lista = [10,40,50,100]
i = 0
suma = 0
while i < 4:
print(lista[i])
i = i+1
lista.append(1000) #Agrega un nuevo obj al final de la lista
lista.insert(2,33) #Inserta un nuevo obj en el indice elegido
#lista.insert(posicion, valor)
del(l... |
7c44987d226a5f0aeba1bffa85ad1de10ff66990 | crazykuma/leetcode | /python3/0104.py | 915 | 3.640625 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxDepth1(self, root: TreeNode) -> int:
# 递归,其实是后序遍历,求出左节点的值与右节点的值比较取大值+1作为树根节点的值
if not root:
return 0
an... |
d392d3e8469e257a30eb4634b4313227870e4425 | BearachB/Hello_World | /Assignment_1/test_1.py | 2,474 | 4.1875 | 4 |
#Get word function goes here to generate the list of words.
def get_word_list():
""" Return a list of words from a word_list.txt file. """
data_file = open("word_list.txt", "r")
word_list = [] # start with an empty word list
for word in data_file: # for every word (line) in the file
# strip off e... |
49761afbefd00bf47c7ac8e816ebb06478a7dd5a | spillay/AHRM | /EmoService/WebSrv/utilities/utilmath.py | 800 | 3.53125 | 4 | import sys
python_version = sys.version_info[0]
if python_version != 2 and python_version != 3:
print('Error Python version {0}, quit'.format(python_version))
exit(0)
def get_3d_centroid(data_list_3d):
xx = []
yy = []
zz = []
for x,y,z in data_list_3d:
xx.append(x)
yy.appe... |
3629084157204285c8f6b07f94254bb7c20b43b3 | Ydeh22/QuantumComputing | /SuperdenseCoding.py | 2,952 | 3.6875 | 4 | '''
File: SuperdenseCoding.py
Author: Collin Farquhar
Description: An an example of superdense coding where two entangled qubits
are entangled and then given separately to two parties (Alice and Bob).
Alice wants to send a two (classical) bit message to Bob and can do so by applyin... |
7f367924f8f6216c6cfae4c02c3db6f5db944648 | pooyamb/py-moneyed | /moneyed/money.py | 8,073 | 3.6875 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
from __future__ import unicode_literals
from decimal import Decimal
import sys
import warnings
PYTHON2 = sys.version_info[0] == 2
# Default, non-existent, currency
DEFAULT_CURRENCY_CODE = 'XYZ'
def force_decimal(amount):
"""Given an amount of unknown ty... |
8a84cd28897a551935e13257e313ac813d07a762 | ShiJingChao/Python- | /PythonStart/一阶段查漏补缺/Day1.py | 1,839 | 3.625 | 4 | # 小数在运算涉及到二进制问题
# a = 0.1+0.2
# print(a)
# if (round(0.1) + round(0.2)) == round(0.3):
# print(True)
# else:
# print(False) # True
"""
高级版
4位验证码:
要求不能重复,且必须含有字母
"""
# import random
# str = ""
# s_str = set()
# letter = [chr(i) for i in range(65,91)]
# letter1 = [chr(i) for i in range(97,123)]
# letter.ex... |
43dbcb31f9c0d34cbc33fe8e646bd9daedf770f8 | Shahzaib1999/Python | /calc.py | 633 | 3.6875 | 4 | from tkinter import *
top=Tk()
top.geometry("400x250")
n1=IntVar()
n1.set("")
n2=IntVar()
n2.set("")
n3=IntVar()
n3.set("")
def add(n1,n2):
add=n1+n2
n3.set(add)
number1=Label(top,text="number 1")
number1.grid()
number2=Label(top,text="number 2")
number2.grid(row=1)
result=Label(... |
3be346cfa3394f7714383a42d7218f4675c5faee | Riceair/Python_homework | /week_9/Part2_41to60_43.py | 162 | 3.5625 | 4 | a_list = ['apple',('Danny','Rob'),'ball']
print("a_list =",a_list)
var1, var2, var3 = a_list
print("var1 =",var1)
print("var2 =",var2)
print("var3 =",var3)
|
38b6ea977f21e35243fa66b48af67f33a6c41f26 | jeanjoubert10/Simple-Pong-in-python-3-and-Turtle-with-start-and-game-over-screen | /bounce.py | 1,932 | 3.9375 | 4 | # Very simple ball paddle game J Joubert 4 Nov 2019
# Writtten on mac osx - may need minor changes for windows as shown
# This code can be copied, changed, updated and if improved - please let me know how!!
import turtle
#import time # and time.sleep(0.017) windows?
win = turtle.Screen()
win.title('Paddle Game')
win... |
5d56167607f7c35940b177daadea7e0cdb7c8d38 | xichengxml/python-tutorial | /src/geektime/01/T007_If.py | 87 | 3.75 | 4 | x = 'abc'
if x == 'abc':
print('x和abc相等')
else:
print('x和abc不相等') |
cc41dd5a7f3a1f5d46f1e5384ec9b2447fe309d3 | lies98/Programmation-Concurrente | /tp3_amarouche_lies.txt | 3,079 | 3.59375 | 4 | import time
def count_mot(phrase):
cpt = 0
phrase = phrase.strip()
for index in range(len(phrase)):
if phrase[index] == ' ' and phrase[index - 1] != ' ':
cpt += 1
return cpt + 1
def count_mot2(phrase):
mots = [item for item in phrase.split() if item != " "]
return len(mot... |
f839611b8d9f1752c1da179920b5f87de9e20285 | AnkusManish/Machine-Learning | /Week2/Sets/Program_3.py | 227 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 31 22:49:49 2019
@author: ankusmanish
"""
a = set([1,2,3,4,5])
#add() method adds the element to the set
a.add(6)
print('Updated list is : {}'.format(a)) |
02ba62b13fb59a5c8576d2b7d07670b05c5c6e78 | CriSarC/PythonExercises | /3.Condicionales/3.1OperadoresRelacionales.py | 205 | 3.875 | 4 | # -*- coding: utf-8 -*-
Num1 = 50
Num2 = 10
Num3 = 100
Num4 = 100
print(Num1 < Num2)
print(Num1 > Num2)
print(Num1 <= Num2)
print(Num1 >= Num2)
print(Num3 >= Num4)
print(Num1 != Num2)
print(Num3 != Num4) |
d37ef098f66adce79d910c1b6ceb34603740dfcb | kawmaiparis/Comsci_AS | /Pre Release - Book/Task 2.py | 1,024 | 3.875 | 4 | while True:
print("1. display the file contents")
print("2. search the array for a particular book")
print("3. end the program")
choice = input("") #DECLARE choice : string
if choice == "1":
myfile = open('BOOK-FILE.txt','r') #DECLARE myfile : file
top = [line.replace("\n","") for li... |
0b9935ccc90e7698e62ea3d19b2a7532a9d03ca1 | ashish-dalal-bitspilani/python_recipes | /python_cookbook/edition_one/Chapter_One/recipe_four.py | 1,750 | 4.4375 | 4 | # Chapter 1
# Section 1.4
# Getting a value from a dictionary
# Problem context : We want to obtain a value from a dictionary,
# without having to handle an exception if the key for which the value is
# being sought is not in the dictionary
# Approach 1
print()
colors = dict(red = 1, green = 2, blue = 3)
print('co... |
c810cbebae3077e83cf151ee08233bd781339787 | fcdmoraes/aulas_FitPart | /aula4_string.py | 412 | 4.0625 | 4 | x = "isso é um string"
print(x)
##print(x[0])
##for letra in x:
## print(letra)
##x[0]='o'
##print(x.upper())
##print(x)
##x = x.upper()
##print(x)
##print(x.lower())
##print(x.title())
##print(x.capitalize())
##lista = list(x)
##print(lista)
##lista[0] = 'o'
##print(lista)
##
##print("/".joi... |
fe146ee7fd16aa8c09a647885a1371198f3c6144 | Finn969/Homework | /returnPosition.py | 218 | 3.8125 | 4 | def returnPosition(string, char):
if char in string:
newstring = string.replace(' ','')
return newstring.index(char) + 1
else:
return -1
print(returnPosition("This is a Sentence","s")) |
dae2c1ce94f5b95a79cae0fb6618bfa57888d467 | Emirates2008/Tarun_2008 | /rectangle.py | 232 | 3.625 | 4 | import turtle
screen = turtle.Screen()
#screen.bgcolor("purple")
line = turtle.Turtle()
line.color("green")
line.fillcolor("orange")
for i in range(2):
line.forward(90)
line.right(90)
line.forward(70)
line.right(90)
|
b82a96690d548302850e9dc453fd54a0fade8443 | Md-Saif-Ryen/roc-pythonista | /Basic Programs/Infinite_monkey_theorem.py | 1,539 | 4.28125 | 4 | """
1, import random
2, user input
3, function to generate a random string of same length as user input.
4, function to compare the randomly generated string to the user's string and giving it a score each time it generates and compare.
"""
import random
def random_str(user_str):
"""This function will produce a r... |
45461ac07c8b4e98177638eeda44f00799ff66e9 | ian-garrett/CIS_122 | /Assignments/Week 4/Lab4-2.py | 1,106 | 4.09375 | 4 | # Ian Garrett
# Lab4-2
def get_int(prompt_message):
"""(str) -> int
displays prompt message,
gets input from user
converts input string to number,
returns number to caller
"""
prompt = prompt_message + ' '
temp = input(prompt) # get input from user
return int(temp)
... |
5832aee986392d800f03c7dbe3a25be4fc4af173 | PJHalvors/Learning_Python | /ZedEx1to4.py | 3,415 | 4.25 | 4 | #!/bin/env/python
#This program contains exercises Num1 to Num4 from Zed's Book
#Excercise 1: Printing strings
#In this exercise using the print command, print seven strings
#The text in a few of the strings may have slightly been changed, only to test, break, and re-build code
#You can use a pair of single or double ... |
ec9477c9b3ffefaf0758ae0b0947941db48650a4 | rng-atb/rng-hackathon | /tools/generate_data.py | 1,525 | 3.5 | 4 | import argparse
import random
def generate_data(num_accounts, labels, num_lines, output=None):
print("""
num accounts: {0}
labels: {1}
num_lines: {2}
""".format(num_accounts, labels, num_lines))
labels = labels.split(",")
data = []
for a in range(num_accounts):
for l i... |
1cf8b3e011bcb391c3ae40f70da3afeee4c63a2d | christopher-beckham/bio-algorithms | /algo-heights/ins.py | 365 | 3.953125 | 4 | import sys
def swap(arr, i ,j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
def insertion_sort(arr):
swaps = 0
for i in range(1, len(arr)):
k = i
while k > 0 and arr[k] < arr[k-1]:
swap(arr, k-1, k)
swaps += 1
k = k -1
return swaps
sys.stdin.readline()
arr = [int(x) for x in sys.stdin.readline(... |
73b81a1f8040b47cf35ea3f500d19f4ec6d2aeaf | HidoCan/Programlama_dilleri_yaz_okulu | /2019/2019_TYT_TemelKavramlar_Soru5.py | 690 | 3.8125 | 4 | from math import *
a = input("Kenar sayısı")
b = input("İçerdiği sayı")
c = input ("Küçük kenar sayısı")
d = input("Büyük kenar sayısı")
a = int(a)
b = int(b)
c = int(c)
d = int(d)
x = a/b
x = floor(x)
f = x * c
e = x * d
while e/c > x+1:
e = e+1
break
while f/d < x:
f = f+1
brea... |
ade8f3f7ec772f17e6aaafa614511ec33ed9ce85 | addriango/curso-python | /sintaxis-basica/15.continue.py | 393 | 4.03125 | 4 | ## la palabra clave "continue" ignora todo lo que esta debajo
## de el en la iteracion donde se cumple la condicion
for letra in "python":
if letra =="h":
continue
print(f"viendo la letra {letra}")
nombre = "Adrian David Gomez Rivera"
print(len(nombre))
contador_caracteres = 0
for i in nombre:
i... |
32165ba5122c7ce7d1d3e2a9fb0620356a9c30ab | yorchd3/JNoriega_GW_HW3 | /Part-1/HW_Task3_Email/employee_email_jorge.py | 1,333 | 4 | 4 | # -*- coding: UTF-8 -*-
"""Employee Email Script.
This module allows us to create an email address using employee data from
a csv file.
Example:
$ python employee_email.py
"""
import os
import csv
filepath = os.path.join("employees.csv")
new_employee_data = []
# Read data into dictionary and create a new ema... |
64084796ea507d0b56189fa6838465f15dc4e4d2 | siddharth778/toc | /count_0_and_1.py | 341 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Sep 22 23:17:59 2019
@author: SiddharthPorwal
"""
n=input()
count0=0
count1=0
for i in n:
if i=='0':
count0=count0+1
for x in n:
if x=='1':
count1=count1+1
print("no of 0's in a string are :"+ str(count0))
print("no of 1's in a string... |
6f753d2c0aa21a00b72f481d56aa5b074427a3ba | FarzanRashid/CodingBat-Solutions | /List-1/max_end3/solution.py | 134 | 3.609375 | 4 | def max_end3(nums):
if nums[0] > nums[-1]:
return [nums[0], nums[0], nums[0]]
else:
return [nums[-1], nums[-1], nums[-1]]
|
5729e2f8bd9cbcbf081da97db8bf89913fe6d3ea | alangberg/AED3-TP1 | /Ejercicio 2/convert.py | 890 | 3.5625 | 4 | import sys
def toBase3(n):
if n < 3:
res = []
res.append(n)
return res
else:
res = toBase3(int(n/3))
res.append(n%3)
return res
ls = toBase3(int(sys.argv[1]))
ls.reverse()
res = [0] * (len(ls) + 1) #arreglo de 0s
i = 0
for d in ls:
if d == 2:
# si tiene un 2 lo puedo reemplazar sumando la potencia q... |
2062698cc5a1bead9ca10a70cb2c81acc5da8466 | chriskopacz/ProjectEuler_python | /problem7.py | 598 | 3.875 | 4 | #Chris Kopacz
#Project Euler
#Problem 7 - 10001st prime
"""
By listing the first six prime numbers: 2, 3, 5, 7, 11, 13
we can see that the 6th prime is 13.
What is the 10001st prime number?
"""
import math
def isPrime(val):
stop = math.ceil(math.sqrt(val))
for iter in range(2,stop+1):
if val % iter =... |
ab506552bd1072db8c7bb8836f9cca9edb5b37a9 | L1nwatch/leetcode-python | /19.删除链表的倒数第N个节点/solve.py | 2,113 | 3.859375 | 4 | #!/bin/env python3
# -*- coding: utf-8 -*-
# version: Python3.X
"""
"""
import re
from typing import List
__author__ = '__L1n__w@tch'
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeNthFromEnd(self, head: L... |
4252944096740632857a8b620208001820a5ffe9 | CatFootPrint/rl_channel_allocation | /environment.py | 6,143 | 3.8125 | 4 | """
This is the environment which is essentially similar to the bin packing problem.
"""
import numpy as np
class Environment:
"""
This environment info:
state combines the 'channel' and the buffers
action is the placement of the buffer at some position in the 'channel'
On an action being taken, a ... |
b9f8e9ba9b29ddfbdf44bd2dd3ca00f7a6e453b4 | zi-yuan-ch/python | /exercise_010.py | 347 | 3.78125 | 4 | # 实例010:给人看的时间
# 题目 暂停一秒输出,并格式化当前时间。
if __name__ == '__main__':
# method1
import time
print("当前时间为:", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
time.sleep(1)
print("暂停1秒后时间为:", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
|
d4387996de68a55e50ee0c29d38b7e188e0cf52a | kinowaki/python-poker | /card.py | 588 | 3.828125 | 4 | #-*-coding:utf-8-*-
import random
class Card:
amount = 52
def __init__(self):
self.card_nums = [2, 3, 4, 5, 6, 7, 8, 9, "T", "J", "Q","K","A"]
self.card_kinds = ["s", "c", "d", "h"]
self.deck = []
for num in self.card_nums:
for kind in self.card_kinds:
self.deck.append(str(num)+kind)
def shuffle(se... |
54c8070acf415fe7410dde5c719464758b25a713 | AxelGarsal/Python-Retos | /3-5_Suma.py | 387 | 3.921875 | 4 | print('Encuentra la suma de todos los múltiplos de 3 o 5 por debajo de 1000.')
'''la funcion range debe tener dos parametros
poner bien los bloques identadores
'''
suma = 0
for i in range(1, 1000):
if i % 3 == 0 or i % 5 == 0:
suma += i
print(i,suma)
print(suma)
mult = 0
for i in range(1, 1001):
... |
2b5f1fb67f4566e5fdb69ea7015b342f46e5f4b0 | maheshd20/NbaPlayerDetails | /project1.py | 449 | 3.796875 | 4 | import json
myplayer=json.load(open("nbaplayer.json"))
def PlayerSearch(name):
i=1
search=0
for k in range(0,len(myplayer)):
if( (myplayer[k]['firstName'].lower()+' '+myplayer[k]['lastName'].lower())==name.lower()):
print(myplayer[k])
search=1
if(search==0):
... |
c713e2cd97e3d4a9209072281f68b82f1a50a530 | rootid23/fft-py | /bits/hamming-distance.py | 1,345 | 4.375 | 4 | #The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
#Given two integers x and y, calculate the Hamming distance.
#Note:
#0 ≤ x, y < 231.
#Example:
#Input: x = 1, y = 4
#Output: 2
#Explanation:
#1 (0 0 0 1)
#4 (0 1 0 0)
# ↑ ↑
#The above arrows ... |
7b37fe0d2e21e82330ceb119c38bfde32193c51a | vaibhavverma9999/Movie-genre-prediction | /model.py | 5,266 | 3.625 | 4 | #in this model we will predict movie genres using movie plots
#to predict we are using bernoulli naive bayes algorithm
#in this section we import all the required libraries
import pandas as pd
import numpy as np
from sklearn.naive_bayes import BernoulliNB
from sklearn.preprocessing import LabelEncoder
from sklearn.feat... |
20c1964462ff6f46dba9a156d736daa3df2178d9 | Macrichie/python | /general/re/match.start match.end match.re.pattern match.string.py | 594 | 3.515625 | 4 |
In [14]: pattern = "find me"
In [15]: text = "i am in between find me end"
In [16]: match = re.search(pattern, text)
In [17]: match.start()
Out[17]: 16
In [18]: match.end()
Out[18]: 23
In [19]: match.re
Out[19]: re.compile(r'find me', re.UNICODE)
In [20]: match.re.pattern
Out[20]: 'find me'
In [22]: match.strin... |
ea5ba396a4d6d6f698009e654846745708b9e4e8 | johnehunt/python-covid-data-analysis | /scikitlearn_data_prediction/merge_data_files.py | 2,387 | 3.59375 | 4 | import pandas as pd
# UK Gov Covid data downloaded on 20th Oct 2021
COVID_DATA = 'covid_data_overview_2021-10-20.csv'
# Data from the 19th Oct 2021 - only covers 2020 - so want to predict 2021 behaviour
MOBILITY_CHANGE = '2020_GB_Region_Mobility_Report_2021-10-19.csv'
# Load the UK Covid overview data
print(f'Loading... |
b763c1f00360f50874b7c0565f4f64de8f386e5f | BaoCaiH/Daily_Coding_Problem | /Python/2019_05_02_Problem_107_Print_Binary_Tree_Level_Wise.py | 1,627 | 4.0625 | 4 | #!/usr/bin/env python
# coding: utf-8
"""2019 May 2nd - Daily_Coding_Problem #107."""
# <markdown>
# ## 2019 May 2nd - Daily_Coding_Problem #107
#
# Problem: Print the nodes in a binary tree level-wise.
# For example, the following should print 1, 2, 3, 4, 5.
#
# ` 1
# / \
# 2 3
# / \
# 4 5`
# %%
class Node... |
b9978f1676fd697c353ff3b16677509c05120f9d | priyankakumbha/python | /day3/test14.py | 270 | 3.75 | 4 | # a = input("enter some thing")
# print(a)
un = input("enter username:")
pw = input("enter password:")
if un != 'lara':
print('username is incorrect')
if pw != '123':
print('password is incorrect')
if un == 'lara' and pw == '123':
print('login success')
|
714765685fd79f538e55308d32eb0caa5b5b05d5 | jekhokie/scriptbox | /python--learnings/coding-practice/integer_float_division.py | 265 | 3.96875 | 4 | #!/usr/bin/env python
#
# Print integer and floating point division results.
#
if __name__ == '__main__':
a = int(input())
b = int(input())
int_divide = a // b
float_divide = float(a) / float(b)
print(int_divide)
print("%f" % float_divide)
|
4f94f71319218cf04b3ea22fe7d205192611afb1 | hzrg/songqin_course | /python_code/字符串格式化/C_跨行字符串格式化.py | 207 | 3.546875 | 4 | # -*- coding:utf-8 -*-
vs = [('Jack',8756),('Patrick',10000)]
# 跨行字符串,用3个引号
fs = '''
%s salary: %d $
%s salary: %d $
'''
print(fs % (vs[0][0], vs[0][1], vs[1][0], vs[1][1]))
|
603ce91dbde68ecfbf970eb87f21d944fa92814d | ankeoderij/vbtl-dodona | /sequentie 11.py | 298 | 3.515625 | 4 | lengte = float(input("Geef de lengte van de muur (in m): "))
hoogte = float(input("Geef de hoogte van de muur (in m): "))
aantal_breedtes = (lengte + 0.519) // 0.52
aantal_rollen = (aantal_breedtes * hoogte + 9.999) // 10
print("Minimumaantal te kopen rollen:", aantal_rollen)
|
6ea44e5d0d0bc8774ea93423586088372177c6e8 | raghavsaboo/data-structures | /linked_lists/doubly_linked_list.py | 804 | 3.8125 | 4 | class Node:
def __init__(self, val):
self.data = val
self.next_element = None
self.previous_element = None
class DoublyLinkedList:
def __init__(self):
self.head_node = None
self.tail_node = None
def detect_loop(self):
"""
O(n) Time Complexity
... |
14bbdecb6b3278d02abd4f40d790a363376b2e82 | zwakenberg/basictrack_2021_2a | /sessions/week_3/teenage_mutant.py | 384 | 4.03125 | 4 | import turtle
ninja = turtle.Turtle()
screen = turtle.Screen()
screen.title("Teenage Mutant Ninja Turtles")
screen.bgcolor("papayawhip")
for step in range(15):
ninja.forward(50)
ninja.left(120)
# after a complete triangle
print(step, step % 3)
if step % 3 == 2:
ninja.penup()
ni... |
e54831ec857c733ca51b6f6adb1c3dcd9f1746ca | vinceparis95/garage | /machineLearning/frameworks/python/elements/objects/list.py | 254 | 4.15625 | 4 |
# create a list
List = []
print(List)
# create a populated list
List = [1, 5, 9]
print(List)
# print elements 0 and 2
# (first and third item)
print(List[0], List[2])
# add elements to the list
List.append(95)
print(List)
List.append(361)
print(List) |
d34c22597b7fac89572b250c2c52f8df7b2dfd5b | acgis-sun00163/gis4107--day02 | /VikySAndBenS/ex6.py | 594 | 3.84375 | 4 | #-------------------------------------------------------------------------------
# Name: Exercise 6
# Purpose: numbers of bears
#
# Author: chengjiaqi sun
#
# Created: 10/09/2019
# Copyright: (c) cheng 2019
# Licence: <your licence>
#---------------------------------------------------------... |
31e10134d6c2f2e9ab9afd69b7bdcbb914ffcfdb | emurph1/unit5 | /matrixDemo.py | 424 | 4.28125 | 4 | #Emily Murphy
#2017-11-17
#matrixDemo.py - how to create and use matrix (list inside of list)
board = [['a','b','c'],['d','e','f'],['g','h','i']]
def printBoard():
for row in range(0,3):
for col in range(0,3):
print(board[row][col], end = ' ')
print()
printBoard()
row = int(i... |
c34c69c17e43d0c072f2a6c281f64d373b10c0aa | samuelcarvalho1/JogoNIM.py | /NIM.py | 4,284 | 4.125 | 4 | #CAMPEONATO
def campeonato():
rodadas = 1
rodadas_faltantes = 2
while rodadas <= 3:
print()
print(" **** Rodada", rodadas,"de 3", "falta(m) mais", rodadas_faltantes, "****")
print()
partida()
rodadas += 1
rodadas_faltantes -= 1
print()
prin... |
ed169fdb9762326ca5c8334409805ef951b8cbf1 | DeekshaNarang/python | /class obj implementation.py | 290 | 3.703125 | 4 | class Student:
def __init__(self):
self.name=" "
self.rollno="0"
def __init__(self,name,rollno):
self.name=name
self.rollno=rollno
def printValues(self):
print(self.name)
print(self.rollno)
S1=Student("abc","123")
S1.printValues() |
6cdabadccce9924c981fdced4c2ad13f6527a449 | upc-projects/tsp-genetic-algorithm | /server/city.py | 1,083 | 4.15625 | 4 | import numpy as np
# This is the class that represents a city with a name and (x,y) coordinates.
class City:
"""
Represents a city to visit for the traveler salesman into the map
Attributes
----------
name: str
The name of the city
x: int
The horizontal coordinate into the ma... |
866706f2ab2766861704df5df02a3f2846f0e353 | fadedge13/prg-105 | /12.1.py | 368 | 4.09375 | 4 | def main():
number(int(input('How many monkeys are jumping on the bed?')))
def number(times):
count = 0
while count < times:
print(times, ' times the monkeys fell of the bed')
print(times, ' time the mother called the doctor')
times -= 1
print(times, 'number of monk... |
0e21106c733bd9b2cbc8ea817d997aa49e109840 | umerdar/Python | /house_of_trees/basics/functions.py | 309 | 3.578125 | 4 | def hows_the_parrot():
print("WAT")
# hows_the_parrot()
def lumberjack(name):
if name.lower() == 'umer':
print("Umer's a lumberjack and he's the man.")
else:
print("{} sleeps all night and works all day!".format(name))
lumberjack("sleepy")
def counter(count):
print("Hi " * count)
counter(3)
|
a71a9b891fbae1600bf02e4b92489ebe63f43acf | JoniNoct/python-laboratory | /Lab3/func.py | 1,956 | 3.609375 | 4 | import re
def is_one_symbol(start_str):
return bool(re.match(r"^\S$", start_str))
def is_integer(start_str):
return bool(re.match(r"^[+-]?\d+$", start_str))
def is_negative_integer(start_str):
return bool(re.match(r"^[-]?\d+$", start_str))
def is_positive_integer(start_str):
return bool(re.match(r"^... |
7fe5d9cc487317d3ff1429e57b09e52bd9bbf3b6 | aman-singh7/training.computerscience.algorithms-datastructures | /01-algorithm-design-and-techniques/2_algorithmic_warmup/fibonacci_sum_last_digit.py | 1,029 | 3.875 | 4 | #Last Digit of the Sum of Fibonacci Numbers:
#Problem Introduction:
#The goal in this problem is to find the last digit of a sum of the first n Fibonacci numbers.
import sys
from fibonacci_huge import get_fibonacci_huge
def fibonacci_sum_naive(n):
if n <= 1:
return n
previous = 0
current = 1
... |
945138709d1e187471d3b34b161a6acd3610ecd5 | Leandro1391/learn-python | /leccion02/personAge.py | 395 | 3.9375 | 4 | age = int(input(f'Input your age: '))
if (age >= 20 and age < 30) or (age >= 30 and age < 40):
print(f'Dentro de rango (20\'s) o (30\'s)')
# if (age >= 20 and age < 30):
# print('Dentro de los 20\'s')
# elif (age >= 30 and age < 40):
# print('Dentro de los 30\'s')
# else:
# pri... |
a46367163f4f40bd0def22719ada088a1c019f9e | jalexvig/algos_datastructures | /string_search/aho_corasick.py | 2,398 | 3.859375 | 4 | """
Search for patterns in text.
Summary:
1. Construct a [trie](https://en.wikipedia.org/wiki/Trie) of the patterns.
2. Recursively determine fail states by looking at parent's fail state.
3. Use trie to create DFA with non-matches following to fail states.
Characteristics:
* `m` = length of all pat... |
2676849b33f9426c2683c995a96502662ea2e7bc | iamrishap/PythonBits | /InterviewBits/hashing/copy-list.py | 1,978 | 4.125 | 4 | """
A linked list is given such that each node contains an additional random pointer which could point to any node in
the list or NULL.
Return a deep copy of the list.
Example
Given list
1 -> 2 -> 3
with random pointers going from
1 -> 3
2 -> 1
3 -> 1
You should return a deep copy of the list. The returned ans... |
296a7bfe4936869d43f8e2720e3f01ce98c4611e | CodingHaHa/PythonBase | /02Python基本语法/11编码/01编码.py | 325 | 3.734375 | 4 | #在win上不能以r模式打开,但是在Linux上就可以
# f = open("txt.txt","r")
#解决中文乱码,添加,encoding="utf8")
# f = open("txt.txt","r",encoding="utf8")
# print(f.read())
# print("中国馆")
# print(["中国馆"])
s = "中国"
print(type(s))
print(len(s))
s = u"中国"
print(type(s))
print(len(s)) |
8960a1747859414cd4e7bc80cc1c0a8531531163 | christ134/mean-stack-dev | /ICTA_CALICUT/python/largest.py | 577 | 4.21875 | 4 | # num1=int(input("Enter first number "))
# num2=int(input("Enter second number "))
# num3=int(input("Enter third number "))
# if(num1<num2):
# l=num2
# else:
# l=num1
# if(num3<l):
# l=l
# else:
# l=num3
# print("largest is: ",l)
def largest(x,y,z):
if(num1<num2):
l=num2
... |
845c6495347c77893b67f2fd675667a1ba17d2e7 | cfw123/pylearn | /basePython/08_objectOriented/hm_05_initMeth.py | 209 | 3.59375 | 4 | class Cat:
def __init__(self):
print("This is init Method")
self.name = "tom"
def eat(self):
print("%s like eat finsh" % self.name)
tom = Cat()
print(tom)
print(tom.name)
|
640d288868b7bf5e64084103c63fd10ed7a5a6df | shankardengi/DataStructure | /firsthighst_secondhigst_other_approch.py | 1,602 | 4 | 4 | class node:
def __init__(self,data):
self.data = data
self.next = None
@staticmethod
def creat_list(n):
first = None
cur = first
for i in range(n):
data = int(input("Enter Data to list:"))
nodes = node(data)
if first == None:
... |
e693d1ec61872e689fd55f85ae2605a73894e043 | Apm96/Ejercicios_Secuenciales_Condicionales | /ejercicios_condicionales.py | 8,836 | 4.0625 | 4 | # 1 Hacer un algoritmo que calcule el total a pagar por la compra de
# camisas. Si se compran tres camisas o mas se aplica un descuento
# del 30% sobre el total de la compra y si son menos de tres camisas
# un descuento del 10%.
valorCamisas = int(input("Digite el valor de las camisetas a comprar "))
numCamisas... |
fbc6259a223a30ccfbd67be4ec0501a9c9689fa8 | david3de/CruzHacks-x-SWE-Pre-Hackathon-Python-Workshop | /numbers.py | 208 | 3.890625 | 4 | # Basic int and float arithmetic
x, y = 27, 13
sum = x + y
diff = x - y
prod = x * y
quot = x / y
mod = x % y
print('Sum: %d, Difference: %d, Product: %d, Quotient: %d'
% (sum, diff, prod, quot))
|
53d57ef73b508e589bc0e27022ab9e06eb1febca | Mkurtz424/n00bc0d3r | /Projects/CodingBat/List-2/List-2 count_evens Mike.py | 188 | 3.828125 | 4 | def count_evens(nums):
evencount = 0
x = 0
while x < len(nums):
if nums[x] % 2 == 0:
evencount = evencount + 1
x = x + 1
else:
x = x + 1
return evencount
|
0c007e12530793ac89e4b93e660be15feb9a2a12 | nadaAlqahtani/Images-Processing | /Pillow.py | 1,406 | 3.75 | 4 | from PIL import Image
img = Image.open(r"C:\Users\nadaa\Python Project\Courses\Image Processing Spyder\1.jpg")
print(img.format)
print(img.mode)
print(img.size)
#resize image
small_img = img.resize((200,300))
small_img.save(r"C:\Users\nadaa\Python Project\Courses\Image Processing Spyder\resize_img_sm... |
602c47513c32317e3480ca64e76f49026542ae63 | MychalCampos/Udacity_CS101_Lesson4 | /add_page_to_index.py | 938 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 01 22:14:46 2015
# Define a procedure, add_page_to_index,
# that takes three inputs:
# - index
# - url (String)
# - content (String)
# It should update the index to include
# all of the word occurences found in the
# page content by adding the url to the
# word's a... |
16b905142b1e0f6eaf7e0685f18bdcd7365c9d96 | WeiChienHsu/Coursera_DS_Algorithm_HW | /Algorithmic_ToolBox/Week 3/covering_segments/covering_segments.py | 722 | 3.6875 | 4 | # Uses python3
import sys
from collections import namedtuple
Segment = namedtuple('Segment', 'start end')
def optimal_points(segments):
seg_text = segments
points = []
inx = segments[0][1]
a = 0
for i, j in segments:
if inx < i:
points.append(inx)
inx = j
i... |
2be1c4381a7080c3177292f991d3829864f76843 | raunakshakya/PythonPractice | /Classes & Objects/08_multiple_inheritance.py | 864 | 4.4375 | 4 | # https://www.javatpoint.com/multiple-inheritance-in-python
"""
Multiple Inheritance allows us to inherit multiple parent classes. We can derive a child class from more than one base
(parent) classes. The multi-derived class inherits the properties of all the base classes.
"""
class First(object):
def __init__(s... |
0c88e664f178607a97d6791cc3968941400f2b6c | jacobpad/cs-hash-tables | /applications/01_lookup_table/lookup_table.py | 1,125 | 3.65625 | 4 | # Add required imports
import random
import math
# Add non-required imports
import time
def slowfun_too_slow(x, y):
v = math.pow(x, y)
v = math.factorial(v)
v //= x + y
v %= 982451653
return v
# Gotta have webster
webster = {}
def slowfun(x, y):
"""
Rewrite slowfun_too_slow() in here... |
3054900cd89e800d30bc76910a2b427dd8fdeee5 | chandanadasarii/CrackingTheCodingInterview | /CrackingTheCodingInterview/Stacks/minium.py | 711 | 3.6875 | 4 | class minStack:
__values = list()
__minval = list()
def push(self, data):
self.__values.append(data)
minval = self.getmin()
if minval and data < minval:
self.__push_min(data)
def __push_min(self, data):
self.__minval.append(data)
def peek(self):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.