blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
733e38312e73bd0ec4cc2c27f571dcbdbd94197f | kyledgls/pdxcodeguild_assignments | /Python/week4/lab28-socks.py | 549 | 3.765625 | 4 | """
sock sorter
original version by Kyle Douglas
"""
import random
sock_types = ['ankle', 'crew', 'calf', 'thigh']
i = 0
laundry = []
while i < 100:
laundry.append(random.choice(sock_types))
i += 1
print(laundry)
sorted_laundry = {}
lone_rangers = {}
for sock in laundry:
if sock not in sorted_laundry:
... |
d56d83109a66b60b73160c4a45d770d01ef76274 | Stuff7/stuff7 | /stuff7/utils/collections/collections.py | 1,021 | 4.1875 | 4 | class SafeDict(dict):
""" For any missing key it will return {key}
Useful for the str.format_map function when
working with arbitrary string and you don't
know if all the values will be present. """
def __missing__(self, key):
return f"{{{key}}}"
class PluralDict(dict):
""" Parses keys with the form "k... |
8678b04cd9e28847b30d4b8ec7fe3f9aaddc1708 | rohan8594/DS-Algos | /leetcode/medium/Arrays and Strings/ReverseWordsInAString.py | 1,076 | 4.3125 | 4 | # Given an input string, reverse the string word by word.
# Example 1:
# Input: "the sky is blue"
# Output: "blue is sky the"
# Example 2:
# Input: " hello world! "
# Output: "world! hello"
# Example 3:
# Input: "a good example"
# Output: "example good a"
# Note:
# A word is defined as a sequence of non-space... |
40ff7f550216205131dcf6131c150505925fbfce | BlackBloodLT/URI_Answers | /Python3/1_INICIANTE/uri1021.py | 4,341 | 4.03125 | 4 | """
Notas e Moedas
Leia um valor de ponto flutuante com duas casas decimais. Este valor representa um valor monetário. A seguir, calcule o
menor número de notas e moedas possíveis no qual o valor pode ser decomposto. As notas consideradas são de 100, 50, 20,
10, 5, 2. As moedas possíveis são de 1, 0.50, 0.25, 0.10, 0.0... |
bdea8daa6a256f3a3253063a841b6c0f2f8e51ca | Jucindra/minimundo-eletrodomesticos-apgsi | /appliances_store.py | 1,148 | 3.765625 | 4 | from datetime import date
class Customer():
def __init__(self, my_id, name, address):
self.id = my_id
self.name = name
self.address = address
class Product():
def __init__(self, my_id, mark, model, serial_number):
self.id = my_id
self.mark = mark
self.model = m... |
24ff6652d849d61879c95a0b778157f79031071c | RyanCrowleyCode/StudentExercises | /reports.py | 2,006 | 4.25 | 4 | # sqlite3 allows python to access the database
import sqlite3
from student import Student
class StudentExerciseReports():
'''Methods for reports on the Student Exercises Database'''
def __init__(self):
# creating a variable to hold the exact path on my computer to the database
self.db_path =... |
d4763ee0ca83d71576c8fb5641804b019051f15b | caiquemarinho/python-course | /Exercises/Module 04/exercise_31.py | 185 | 4.1875 | 4 | """
Read a number and prints the number that comes before it and the one that comes after it.
"""
print('Please, insert a number')
num = int(input())
print(f'{num-1} and {num+1}')
4 |
7337154c0f16690df6ead64ff37212285897cc20 | vdloo/dotfiles | /code/scripts/fun/quicksort_functional.py | 409 | 3.84375 | 4 | #!/usr/bin/env python
import random, string
random_digits = map(lambda _ : random.randint(0, 10), range(0, 10))
def quicksort(seq):
if len(seq) > 1:
left = filter(lambda x: x < seq[0], seq[1:])
middle = seq[:1]
right = filter(lambda x: x >= seq[0], seq[1:])
return quicksort(left) ... |
19189414320d7e176d50725f259ba25fa44d65ba | alonzo-olum/py-algo | /anagram.py | 368 | 4.03125 | 4 | #!/bin/env python3
from collections import Counter
import cProfile
def anagram(first_string, second_string):
if Counter(first_string) == Counter(second_string):
return True
# Main Program Block
first_string = "algorithm"
second_string = "logarithm"
print(anagram(first_string, second_string))
#print(cProfi... |
3e2c76d4a779d3559f3b800c5fd083ebfb5d4ca2 | crileiton/curso_python | /5 Entradas y salidas de datos/tabla.py | 522 | 3.8125 | 4 | # Ejercicio No. 2
import sys
if len(sys.argv) == 3:
filas = int(sys.argv[1])
columnas = int(sys.argv[2])
if ( (filas > 0 and filas < 10) and (columnas > 0 and columnas < 10) ):
for fila in range(filas):
print("")
for columna in range(columnas):
print("*", end... |
a912c8189096a069ef1684385f55191d3a160fdd | mani5348/Python | /Day3/Third_Largest_No.py | 213 | 4.5 | 4 | #write a program to Find the 3rd Largest Number in a List
list=[1,2,4,32,5,8,4,9,10,15]
list.sort()
print("sorted list is :",list)
len1=len(list)
print("Third largest element in the list is :",list[len1-3])
|
b6a6b915b2ade7f035d4ddebc105f1476256347a | DavidSchmidtSBU/DavidSchmidtSBU.github.io | /Bible.py | 788 | 4.1875 | 4 | # First find a bible in text form
inFile = open('KJV12.TXT', 'r')
longWord = " " #Initialize longWord
inLine = inFile.readline() #Read in a line of text
while (inLine != ''): #While more lines to read
lineList = inLine.split(' ') #Split words into a list
# Look through the lis... |
2878c3f8a5b9180bc5d2eea6399fba16ab06922f | MarkisDev/python-fun | /Competitive Programming/binary-triangle.py | 772 | 4.125 | 4 | """
Binary Triangle
This script prints a Binary Triangle with inputted number of lines.
@author : MarkisDev
@copyright : https://markis.dev
@source : https://www.geeksforgeeks.org/program-to-print-modified-binary-triangle-pattern/
"""
# Taking input from user for number of lines
number = int(input("Enter the nu... |
b34c39f1f5be55530badcbf5254deeb24a3c2ae5 | thaismr/pythonAdvanced | /Collections/05_ordered_dict.py | 452 | 3.71875 | 4 | from collections import OrderedDict
def main():
scores = [
("Name", (18, 12)),
("Name 2", (10, 8)),
("Name 3", (15, 9))
]
sorted_scores = sorted(scores, key=lambda t: t[1][0], reverse=True)
print(sorted_scores)
scores = OrderedDict(sorted_scores)
print(scores)
nam... |
cb9cd760d9d1f6857fdaf91c34b7af869c8c55b0 | alanjvano/pi_hexa | /math_hw.py | 95 | 3.75 | 4 | x = True
a = 0
while x < 100:
x = x+1
print('{}: {}, {}'.format(x, 6*x-1, 6*x+1))
|
e46b24d0ae1ff6a8e843f4ff1813b751c6744641 | lozaeric/icpc_undav | /Kattis/oddities.py | 104 | 4.125 | 4 | n = int(input())
for i in range(n):
m = int(input())
print(m, "is even" if m%2==0 else "is odd") |
326979a28d81b329c96585bdc46a83e47f0c3000 | DAltier/Math_Dojo_TDD | /math_dojo_tdd.py | 732 | 3.578125 | 4 | class MathDojo:
def __init__(self):
self.result = 0
def add(self, num, *nums) :
self.result += num
for var in nums :
self.result += var
return self
def subtract(self, num, *nums) :
self.result -= num
for var in nums :
self.result -= var... |
71412657c69f3f63454dd8a2e3510fcea6d06114 | atveretinov/tests | /HuckerRankProblems/src/min_distance.py | 823 | 4.03125 | 4 | # Consider an array of n integers, A = [a0,a1,...,an-1] . The distance between two indices,i and j, is denoted by
# di,j =|i-j| . Given A , find the minimum di,j such that ai=aj and i!=j . In other words, find the minimum distance
# between any pair of equal elements in the array. If no such value exists, print -1 .
#... |
80e17154c4f7ecb7c16fea243913a4ca5728f1a1 | ack8006/EulerProjects | /prob9-specialPythag.py | 710 | 4.3125 | 4 | """
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
def main():
afterDerivationByHand()
def afterDerivationByHand():
b = 1
while ... |
e704be964d02e7a6cfc9adf16b2932f82d417427 | amogchandrashekar/Leetcode | /Medium/Merge Intervals.py | 789 | 3.875 | 4 | from typing import List
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals.sort(key=lambda x: (x[0], x[1]))
merged_intervals = []
start, stop = intervals[0]
for strt_i, stop_i in intervals[1:]:
# merge the intervals
i... |
1ce42a3233096c9ed90d2709e517665b054094f0 | lyineee/NN_regression | /plot.py | 336 | 3.59375 | 4 | import matplotlib.pyplot as plt
from random import random
import numpy as np
#y = x**2 + 1*random(0,1) - 25
def graph():
x=np.linspace(-5,5,50)
y=np.ones((50,))
for i,data in enumerate(x):
y[i]=data**2 + 1*random() - 25
plt.figure()
plt.plot(x, y)
plt.show()
if __name__ == "__main... |
be72c62328561a2ae507e2838314cbf77818f4cc | 108krohan/codor | /hackerrank-python/algorithm/strings/alternatingCharacters - number of deletrions.py | 1,047 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""alternating characters at hackerrank.com
"""
"""
Shashank likes strings in which consecutive characters
are different. For example, he likes ABABA, while
he doesn't like ABAA. Given a
string containing characters A and B only, he wants to change
it into a string he likes. To do this, ... |
b1dccb6a269c09b4cf894ad37c27fb9469fc3622 | 2470370075/all | /剥皮.py | 226 | 3.75 | 4 | l=[1,2,[2,3,[4]]]
def func(x):
l2 = []
def func2(x):
for i in x:
if isinstance(i,list):
func2(i)
else:
l2.append(i)
func2(x)
print(l2)
func(l)
|
687f38ce0faeddabba0ea5b28cc568413f941812 | Kraszu/mojGitHub | /Python/task2/task2.py | 1,168 | 3.875 | 4 | """Assignment 2
TASK2
Maciej Kubiniec R00144142"""
""" function checks if number given by user is odd or even.
if number is even then is devided by 2.
if number is odd then is multiplay by 3 and 1 is added"""
def reducer(number):
if number % 2 == 0:
print("(",number ,"/ 2 )")
print()
... |
155521d62436f87f2c405656cccd37d12ddd3ed6 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/palindromePermutation.py | 2,550 | 3.828125 | 4 | """
Palindrome Permutation
Given a string, determine if a permutation of the string could form a palindrome.
Example 1:
Input: "code"
Output: false
Example 2:
Input: "aab"
Output: true
Example 3:
Input: "carerac"
Output: true
"""
"""
HashMap
Time: O(N)
Space: O(N)
"""
class Solution(object):
def canPermutePal... |
f036744066ab5df34625447d36a1743af5b9fb72 | kalkins/plab-bbr | /color_sensob.py | 1,993 | 3.703125 | 4 | from math import floor
from sensob import Sensob
from sensors.camera import Camera
class ColorSensob(Sensob):
"""A sensob that detects the amount of a given color in an image."""
expensive = True
def __init__(self, color, threshold=0.3, cut_ratio=(0.5, 0.25, 0, 0.25)):
"""
Initialize the... |
20d8c6f23ce7d9d66b06c0ad66cbd0eeef72e106 | dbsgh9932/TIL | /list/06_list_append_insert.py | 1,441 | 3.96875 | 4 | # append() - 리스트의 끝에 새로운 요소 추가 / 리스트.append(새로 추가할 요소)
a=[1,2,3,4]
a.append(5) # a
print(a)
a.append([6,7])
print(a)
# a.append(8,9) # 2개 이상 원소 불가
# print(a) # TypeError: list.append() takes exactly one argument (2 given)
# 빈 리스트를 생성하고 요소 나중에 추가
values=[]
values.append(10)
values.append(20)
values.append(30)
print(va... |
170907ad0f92f4ee2906b25b287d0136ccf5e452 | gergo091/CodewarChallenge | /first.py | 671 | 3.921875 | 4 | import re
def title_case(title, minor_words=None):
if not minor_words:
return title.title()
else:
splited_title = re.split("\\s", title.title())
splited_minor_words = re.split("\\s",minor_words.lower())
new_title = splited_title[0]
for s in splited_title[1:]:
... |
d5029b798d9528d60577e197ca5dcf460379b6e0 | Netmistro/Py-Practical-Problems | /Chapter 2/2.5.6.py | 131 | 4.21875 | 4 | # 6. Write a program that uses a for loop to print the numbers 100, 98, 96, . . . , 4, 2.
for i in range(100, 0, -2):
print(i)
|
66db4de1548f187d131f4e227182bf542a34a39f | wudongdong1000/Liaopractice | /practice_6.py | 301 | 3.828125 | 4 | #没搞太懂
def move(n, a, b, c):
if n == 1:
print('move', a, '-->', c)
else:
move(n-1, a, c, b)
move(1, a, b, c)
move(n-1, b, a, c)
#计算移动了多少步
move(4, 'A', 'B', 'C')
def f(n):
if n==2:
return 3
return f(n-1)*2+1
print(f(4))
|
8330dd686199cc1515e5595364a6d6fc22e245f6 | ishan793/EE239-Big-Data-Analysis | /Project1_804587205_204617837_004589213_204587029/polynomial/plot_underfitting_overfitting.py | 3,557 | 4.40625 | 4 | """
============================
Underfitting vs. Overfitting
============================
This example demonstrates the problems of underfitting and overfitting and
how we can use linear regression with polynomial features to approximate
nonlinear functions. The plot shows the function that we want to approximate,
wh... |
00feccb1bf7b8c15b0cc4b4c0e8f9d38d9065ed3 | programming-practices/python | /src/main/python/Lista.py | 6,907 | 4.28125 | 4 | # Tanto las Tumpla como las listas son conjuntos ordenados de elementos, no asi los diccionarios.
# Que son las listas:
# Estructura de datos que nos permite almacenar grand cantidad de valores(equivalente a los array en todos lenguajes
# de programacion.
# En Python las listas pueden guardar diferentes tipos de... |
3680bb1c5c4f941e709cd7bca19c16b67366d30c | ahsankhan530/python-practice | /Assignment-5.10.py | 244 | 3.640625 | 4 | current_users=['Ahsan','KASHIF','jawad','abbas','daim']
new_users=[str(input())]
for new_user in new_users :
if new_user in current_users :
print(new_user,"is available")
else:
print(new_user,"is not available")
|
66e4913262b9bdb6df83bd4ba34a1169e107ba85 | panditdandgule/DataScience | /Other/Projects/Dictonary/DictfromkeysAndUpdate.py | 621 | 3.921875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 24 15:54:08 2019
@author: pandit
"""
#fromkeys() and update()
#Intializing dictionary 1
dic1={'Name':'Nandini','Age':19}
#Initializing dictionary 2
dic2={'ID':2541997}
#Initizlizing sequance
sequ=('Name','Age','ID')
#Using update to add dic2 va... |
c8e485c0acc87b563df03e2a54d0f8f82246220e | duy2001x1/nguyenquangduy-fundamentals-c4e14 | /session3/homework/sheep.py | 1,027 | 3.859375 | 4 | sheep = [5, 7, 300, 90, 24, 50, 75]
print("Hello, my name is Duy and these are my flook: ")
print(sheep, sep = ', ')
print()
sheep_boss = max(sheep)
print("Now my biggest sheep has size",sheep_boss,"!", "Let's shear it!")
ind = sheep.index(max(sheep))
default = 8
sheep[ind] = default
print("After shearing, here is my... |
e065555c5f291f462cfccbc461106026f6c0aa9f | snlab/odl-summit-2016-tutorial-vm | /utils/Maple_Topo_Scripts/exampletopo.py | 1,676 | 3.640625 | 4 | """Custom topology example
Two directly connected switches plus a host for each switch:
host --- switch --- switch --- host
Adding the 'topos' dict with a key/value pair to generate our newly defined
topology enables one to pass in '--topo=mytopo' from the command line.
"""
from mininet.topo import Topo
from min... |
e63e4d6a4b4272a44249d7224f64b6377ba30d2b | sahansera/algo-src | /problems/common_elements_sorted_arrays/run-no-ds.py | 936 | 3.984375 | 4 | # No DS and onnly using pointers
def common_elements(list1, list2):
result = []
p1 = 0
p2 = 0
# we can't rely on the array length. hence, while
while p1 < len(list1) and p2 < len(list2):
if list1[p1] == list2[p2]:
result.append(list1[p1])
p1 += 1
p2 += 1
... |
54963f02efb2c3d9712229d20664fca2fb38e406 | SereDim/Trash | /36.py | 537 | 4.03125 | 4 | '''
Знайти суму додатніх елементів лінійного масиву цілих чисел.
Розмірність масиву - 10. Заповнення масиву здійснити з клавіатури.
Серебренніков Дмитро
'''
c=0#
for a in range(10):#диапазон
b=int(input())#ввод
if b>=0:#условие при котором будут сумироватся только положительные числа
c=c+b#сумм... |
6cbafa6915d044d467fe62a06c1f41a4bd26fc64 | oakoak/5_lang_frequency | /lang_frequency.py | 1,287 | 3.609375 | 4 | import string
from collections import Counter
import sys
import argparse
def load_data(filepath):
with open(filepath, "r") as file:
return file.read()
def get_most_frequent_words(text, number_of_words):
all_words = filter(None, [word.strip(string.punctuation)
for word in te... |
9ccd30bb1c2f91c954f35cbe9f6af6c75c0b96ec | xcsp3team/pycsp3 | /problems/csp/single/Dinner.py | 679 | 3.734375 | 4 | """
My son came to me the other day and said, "Dad, I need help with a math problem."
The problem went like this:
- We're going out to dinner taking 1-6 grandparents, 1-10 parents and/or 1-40 children
- Grandparents cost $3 for dinner, parents $2 and children $0.50
- There must be 20 total people at dinner and it must ... |
e8682307d0780ac047907e6f9f11ed73ae4ef743 | AnjalBam/IWassign-data-types-functions-python | /data_types/5_add_ing_or_ly.py | 621 | 4.5625 | 5 | """
5. Write a Python program to add 'ing' at the end of a given string (length
should be at least 3). If the given string already ends with 'ing' then add
'ly' instead. If the
string length of the given string is less than 3, leave it unchanged.
Sample String : 'abc'
Expected Result : 'abcing'
Sample String : 'string'... |
9d9c25d7efbee35e1cd76b14ab9fea79301c096f | pedr0diniz/cevpython | /PythonExercícios/ex095 - Aprimorando os Dicionários.py | 2,236 | 3.984375 | 4 | # DESAFIO 095 - Aprimore o DESAFIO 093 para que ele funcione com VÁRIOS JOGADORES, incluindo um sistema de visuali-
#zação de DETALHES DO APROVEITAMENTO de cada jogador.
dicio = {}
partidas = idjog = 1
gols = []
controle = 'S'
jogadores = []
while controle == 'S':
dicio['nome'] = str(input('Nome do Jogador: '))
p... |
c56d4b94b95e82c801bfc1ee556a5a83f413073a | WinrichSy/HackerRank-Solutions | /Python/Collections.OrderedDict.py | 511 | 3.96875 | 4 | #Collections.OrderedDict()
#https://www.hackerrank.com/challenges/py-collections-ordereddict/problem
from collections import OrderedDict
items = int(input())
ordered_dict = OrderedDict()
for i in range(items):
item_price = input().split()
item = ' '.join(item_price[0:-1])
price = int(item_price[-1])
i... |
6a6716391aae23c09e74170692f8bd6debe4339a | Visheshjha09/project_sorting_visualization_using_python_gui | /quickSort.py | 2,403 | 4.125 | 4 | #Like Merge Sort, QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and
#partitions the given array around the picked pivot. There are many different versions of quickSort that pick pivot in different ways.
#Always pick first element as pivot.
#Always pick last element as pivot (implemented bel... |
631080fdd12a02c3f77d9a9a4dba5535604c8045 | ParulProgrammingHub/assignment-1-bansiundhad | /q7.py | 307 | 4.4375 | 4 | # program to calculate third angle using function
angle1=input("enter the 1st angle :")
angle2=input("enter the 2nd angle :")
def thirdangle(angle1,angle2):
angle=180-(angle1+angle2)
return angle
print "the third angle is :%s" %thirdangle(angle1,angle2)
r=raw_input("press any key to exit")
|
4e7b68984abf439ec9237b9a0c9f3e0aeb8bbe47 | Hoon94/Algorithm | /Programmers/단속카메라.py | 400 | 3.53125 | 4 | def solution(routes):
routes = sorted(routes, key=lambda x: x[1])
last_camera = -30000
answer = 0
for route in routes:
if last_camera < route[0]:
answer += 1
last_camera = route[1]
return answer
if __name__ == "__main__":
# Test case 1
routes = [[-20, 15... |
039da223b1fe70e997d677b225ab46453a9d5b82 | used-for-me/ProjectName | /windows下的编程/SystemChangeManager/findfile.py | 620 | 3.59375 | 4 | import os
import os.path
# os.chdir('/')
#
# print([filename for filename in os.listdir('./')])
my_path = []
def list_dir_depth(directory):
for filename in os.listdir(directory):
path = os.path.join(directory, filename)
if os.path.isfile(path):
my_path.append('f_'+path)
elif ... |
af6da1dfb4a369e98ea0d896afaa1a2766a16d93 | saipavans/programming_winter | /winter_lab_4/ATask1.py | 832 | 4.125 | 4 | def capitalize_all(t):
res = []
for s in t:
res.append(s.capitalize())
return res
def check_nested_list(input_list):
for element in input_list:
if isinstance(element, list):
return True
return False
def capitalize_nested(nested_string_list):
res = []
if isinst... |
864928c047602e58e6091b5ca0350ac198187cb6 | akshaykumar34/Email-slicer | /EMAIL SLICER.py | 230 | 4 | 4 | email=input("What is the email address:").strip()
user = email[:email.index("@")]
domain = email[email.index("@")+1:]
output = "Your email is {} and your username is {} and domain is {}".format(email,user,domain)
print(output) |
149ee84b0a9fca234751783908dd1e92b84ae856 | BobcatsII/pyscript | /test2.py | 681 | 3.78125 | 4 | import random
times = 0
total = 0
while True:
choise = input('1.begin,2.close\n')
if choise == 1:
total += 1
num = random.randint(1,50)
while True:
gue = int(input("please guess my input:"))
times += 1
if gue > num:
print "too big"
... |
8ff10312196ea5bd89c6b036f094aa707dfb149d | manas1410/Spectrum-Internship_2020 | /Write a python program to print all the prime number in a given interval and also check is a given input number is prime or not..py | 1,049 | 4.3125 | 4 | #Write a python program to print all the prime number in a given interval and also check is a given input number is prime or not.
def prime(x):#function to check a number is prime or not
c=0#counter value
for i in range(1,x+1):
if(x%i==0):
c=c+1
if(c==2):
return (True)
... |
b2d7299f532847b901829b17f18c20e8d34708d2 | jcspencer/s1_algs | /recursion/binary_search.py | 757 | 4.15625 | 4 | def recursive_binary_search(a_list, target, low, high):
# make sure the list is sorted
a_list = sorted(a_list)
def recursion(first, last):
# find the middle index of the segment
# we're searching in
mid = (first + last) // 2
if first > last:
# not allowed
return None
elif (a_list... |
b858f57d2728a06e3608081fd9bded30392d62d1 | imlifeilong/MyAlgorithm | /leetcode/动态规划/279. 完全平方数.py | 821 | 3.671875 | 4 | '''
输入:n = 12
输出:3
解释:12 = 4 + 4 + 4
'''
class Solution:
def numSquares(self, n: int) -> int:
res = self.process(1, n)
print(res)
def process(self, index, n):
# 目标值为0时,已经被分配完
if n == 0:
return 0
# 当前值平方大于目标值时,需要舍弃这个分支,返回无穷大(因为要取最小值)
if index * inde... |
abc9e63c63e8e6da3ab6f7fb4edf5dc53604a11a | MRS88/python_basics | /week_4_functions/triangle_perimeter.py | 965 | 4.375 | 4 | '''
Напишите функцию, вычисляющую длину отрезка по координатам его концов.
С помощью этой функции напишите программу, вычисляющую периметр треугольника
по координатам трех его вершин.
Формат ввода
На вход программе подается 6 целых чисел — координат x₁, y₁, x₂, y₂, x₃, y₃
вершин треугольника. Все числа по модулю не пр... |
69aeb8c0fd889063fa2bd55d5b071ffb17b8def3 | manisha54/TestProject1 | /functionality/six.py | 160 | 4.125 | 4 | '''
Q.No.6 Write a Python program to reverse a string.
'''
'''
a=input("enter a string: ")
print(a[::-1])
'''
str=input("enter a sentence: ")
print(str[::-1]) |
076f67bd4b747d7e418764cbc97bb605397d01d0 | 2Clutch/briefcase | /src/briefcase/console.py | 1,586 | 4.5 | 4 | import operator
def select_option(options, input=input, prompt='> ', error="Invalid selection"):
"""
Prompt the user for a choice from a list of options.
The options are provided as a dictionary; the values are the
human-readable options, and the keys are the values that will
be returned as the s... |
1b7becbda936221e6cd6b66c6e9c42f0fa53ad76 | kilala-mega/coding-pattern | /rotation-count.py | 553 | 3.890625 | 4 | def count_rotations(nums: List[int]) -> int:
if not nums:
return 0
start, end = 0, len(nums)-1
if nums[start] <= nums[end]:
return 0
while start + 1 < end:
mid = (start + end)//2
if nums[mid] >= nums[start]:
start = mid
else:
end = mid
... |
f889df8bc101874db1d53fc49382ece5e6d43a3b | KoralK5/ScienceFair2021 | /NeuralNetwork/Games/Snake/snakeNNgame.py | 3,873 | 3.71875 | 4 | import random
import snakeNN
import time
import os
import keyboard
from copy import deepcopy
def show(arr):
for row in arr:
print(''.join(row))
def putApple(arr):
x, y = [], []
for row in range(len(arr)):
for col in range(len(arr[row])):
if arr[row][col] == '⬛':
x += [row]
y += [col... |
95e89d793c1bbc9cafc028cd205ca0db6740020e | OishinSmith/Python-exercises | /2017-02-10/ca117/smitho25/beststudent_v1_22.py | 496 | 3.5625 | 4 | import sys
try:
with open(sys.argv[1], "r") as f:
highest_mark = 0
lines = f.readlines()
for sentence in lines:
sentence = sentence.strip().split(" ")
if int(sentence[0]) > int(highest_mark):
highest_mark = sentence[0]
best_student = " ".join(sentence[1:])
print("Best s... |
699b65b08e547f990563db87c79e6534b238f200 | domoramas/code_guild_projects | /python labs/lab19_2.py | 785 | 3.84375 | 4 | #black jack advice
def blackjack_adv(x,y,z):
card_dict = {
"A" : 1, "2": 2, "3" : 3, "4": 4,
"5": 5, "6" : 6, "7": 7, "8": 8,
"9" : 9, "10" : 10, "J": 10, "Q": 10, "K": 10
}
total = (card_dict[x] + card_dict[y] + card_dict[z])
if total < 12 and "A" in (x,y,z):
total = total + 10
... |
e088abbe422968c52de87f173ae5a055cfc52e8b | zhd785576549/py-utils | /py_utils/validator/phone/cn.py | 1,012 | 3.515625 | 4 | """
This is validate for phone in China
Author: Winter
History:
Version Author Email Date Message
1.0.0 Winter 785576549@qq.com 2019-10-10 Create
"""
import re
def mobile_valid(mobile):
"""
Mobile phone number va... |
4085c413e1fe017f149ae36ee236b914c4752801 | Aasthaengg/IBMdataset | /Python_codes/p03555/s167958170.py | 277 | 3.8125 | 4 | # 文字列を取得
C1 = str(input())
C2 = str(input())
# 文字列の結合
ori_str = C1 + C2
# 末尾から1文字ずつ取得して逆さま文字を生成
rev_str = ori_str[-1::-1]
# 比較結果を出力
if ori_str == rev_str:
print("YES")
else:
print("NO")
|
f886751d183fd3f7f477728e1e031df9c8b76c62 | decadevs/use-cases-python-lere01 | /instance_methods.py | 1,611 | 4.5 | 4 | # Document at least 3 use cases of instance methods
"""
Instance methods are methods that are which are called on the object (instance) of a class. Through
the 'self' parameter, they have access to all attributes and other methods on the same object. Hence,
class methods can modify the said attributes. The instance me... |
d0cee4073f5e7054da8edaf68798d89b6fad9a0c | fxmike/bootcamp | /github challenge/#17.py | 728 | 3.78125 | 4 | # Question:
# Write a program that computes the net amount of a bank account based a transaction
# log from console input. The transaction log format is shown as following:
# D 100
# W 200
#
# D means deposit while W means withdrawal.
# Suppose the following input is supplied to the program:
# D 300
# D 300
# W 200
# D... |
5b70c992903e842a2067c2beac039cc064d41207 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/kindergarten-garden/30aafd1f62114511acff8d7b05c32bce.py | 796 | 3.5625 | 4 | class Garden():
def __init__(self, diagram, students=None):
self.diagram = diagram.split('\n')
if students:
self.students = students
self.students.sort()
else:
self.students = ['Alice', 'Bob', 'Charlie',
'David', 'Eve', 'Fred'... |
014875c654d4ed3b125fab06b92979a9b5d6620c | Madara701/Python_OO | /Python_OO/NumeroComParametrodeVariavel.py | 308 | 3.796875 | 4 | def Funcao(*args):
print(args)
Funcao(1,2,3, 'fabio')
'''
a utilização do args serve para poder passa mais de um parametro cqunado declaramos a função ou uma classe
sempre utilizamos * ou ** para transformar em tupla ou dicionario
'''
def F1(**Kwargs):
print(Kwargs)
F1(nome ='Fabio',idade=25)
|
57b7de2b232d702d472aac32bf8795a3646c95d2 | yashwinder/Geo-Visualizer_and_Analysis_Tool | /clipmosaic.py | 8,665 | 3.6875 | 4 | '''Function to perform clipping on the mosaic file. The input mosaic is provided in .tif file.
Clipping is basically cropping the input image according to the given dimensions.
These dimesions are specified as 'xmax', 'xmin', 'ymax' and 'ymin'.
Main libraries used are tkinter, rasterio, shapely, geopandas, earthpy, car... |
81bcda5134eee69f105daf20765da1960b0c41d2 | joekimga/python-challenge | /PyPoll/test.py | 167 | 3.734375 | 4 | mydictionary = {'d': 34, 'a': 4, 'b': 18, 'c': 1}
print(mydictionary['d'], end = '')
print(mydictionary.get('d'))
print(max(mydictionary, key = mydictionary.get))
|
8b5da1de7d343b3a4a674a7510e5ec227323a87d | galoryzen/AdventOfCodeChallenge | /2020/06/code.py | 811 | 3.5625 | 4 |
def readFile():
with open(f"{__file__.rstrip('code.py')}input.txt", "r") as f:
return [line.split() for line in f.read().strip().split("\n\n")]
def part1(groups):
i = 0
for group in groups:
s = ""
for answer in group:
s += answer
new_str = "".join(set(s))
... |
7567c0a7ff956992d73cb75d5c53e4b94d5e5544 | xgenOsama/python_learning | /test_Regex.py | 437 | 3.75 | 4 | import re
# \s space charcter * any number of them () group them
print (re.split(r'(\s*)','here is some words'))
# \s space \S not space \d digest \D not digest
# print (re.split(r'([a-f]','adfadfadfbafjkgbjndalsjfadb'))
print (re.findall(r'\w{1,60}\@\w{1,20}\.\w{1,6}','osama@gmail.com'))
pat = re.findall(r'\... |
e96ad6f3f2ead231676185d515d619732ac4908d | durban24k/cell_trilateration | /draw.py | 1,556 | 3.640625 | 4 | import turtle
from random import randint
def drawCellTowers():
myPen = turtle.Turtle()
myPen.hideturtle()
turtle.tracer(0)
myPen.speed(0)
window = turtle.Screen()
window.bgcolor("#F0F0F0")
x1 = randint(-150,-80)
y1 = randint(-150,150)
x2 = randint(80,150)
y... |
148cf1ab0d4f152660491994a08c27b11a57489a | loushingba/loushingbaPyRepo | /strfuns.py | 766 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 17 13:36:05 2020
@author: sanathoi
"""
line=input("Enter a line of text: ")
upcount=lowcount=alphacount=digitcount=specialcount=0
for a in line:
if a.isalpha():
alphacount+=1
if a.isupper():
upcount+=1
else:
... |
0a021f9ff3d5680facff657eb4cdc475b154eb3b | 763272955/python | /practice/大小.py | 320 | 3.5625 | 4 | #-*- coding: utf-8 -*-
import random
import time
input('请输入下注金额'), c
a= random.randrange(1,6)
b = random.randrange(1,6)
if a > b:
print '最大值a为 \n',a
time.sleep(10)
print '最大值a为 \n', a
else:
print '最大值b为 \n', b
time.sleep(10)
print '最大值b为 \n', b
|
e4758b3951d3c9fa0ac533cc37cae523742f1778 | vsdrun/lc_public | /depth-first-search/426_Convert_Binary_Search_Tree_to_Sorted_Doubly_Linked_List.py | 4,354 | 4.3125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/convert-binary-search-tree-to-sorted-doubly-linked-list/
Convert a BST to a sorted circular doubly-linked list in-place.
Think of the left and right pointers as synonymous to the previous
and next pointers in a doubly-linked list.
Let's... |
6a764fd49bb0b8173adf004d9b5177b6145c5653 | liukai234/python_course_record | /函数和lambda表达式/lambda表达式.py | 1,494 | 4.28125 | 4 | '''
lambda表达式:lambda [parameter_list] : 表达式
语法格式要点:1、必须要lambda关键字来定义
2、lambda之后、冒号左边是参数列表,可以没有参数或者多个参数,右边是表达式的返回值
3、只能是单行表达式,本质上是匿名的、单行函数体
'''
# lambda表达式代替局部函数
def get_math_func(type):
'''
def square(n): # 求平方
return n*n
def cube(n): # 求立方
return n * ... |
7c15abb43b81e29e26f5b7011b8c00de217e2e77 | founek2/python | /docs/_assignments/lesson5/assignment/calc_normal.py | 2,145 | 4.21875 | 4 | operator_list = ["+", "-", "/", "*", "q"]
print("Byl spuštěn program Kalkulačka, který umožnuje sčítaní, odečítání, násobení a dělení")
print("Program Vás nejprve vyzve pro zadání čísla, následně Vás vyzve pro zadání matematického operátoru (+,-,*,/), poté k dalšímu číslu")
print("Pokud zadáte matematický operátor jako... |
134b39d21692c18fbd2046c2f371f105ab1bc086 | AndiLi99/gan | /src/deconv_layer.py | 5,840 | 3.5625 | 4 | from kernel import Kernel
import numpy as np
from activation_functions import LeakyRELU
from activation_functions import Sigmoid
# leaky relu function
def func (z):
return LeakyRELU.func(z)
def func_deriv(z):
return LeakyRELU.func_deriv(z)
# Pads an image with zeros given a mapping
# Args:
# image (3D np ... |
955c30593b5c8952a9edef6555ccefd769723532 | DaZhiZi/chest | /problem/pro1.py | 837 | 3.609375 | 4 | def func1():
from itertools import permutations
import json
l = [0, 1, 2, 3]
r = ['{}{}{}'.format(a, b, c) for a, b, c in permutations(l, 3)]
print(json.dumps(r, indent=4))
def func2(length=6):
import random
a = [chr(i) for i in range(97, 97 + 26)]
b = [chr(i) for i in range(65, 65 + 2... |
57942b23653373961a941aa0f1f186139e92887b | Ant-Ross/Programming-for-Social-Sciences | /Python_exercise/18.09.18_notes.py | 1,931 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 18 10:46:18 2018
@author: ts16larp
"""
#TUESDAY 18/09/18
a = "Hey"
#Retrievinig the last element of the string
a[len(a)-1]
a[-1]
#Strings are immutable, i.e. I can't change a single value in it.
#i.e, a[1] = 'a' is not allowed
#Concatenate strings by...
a =... |
f3ca96526b0f432a896bbc8e2e20085a110697b3 | LinnikPolina/Compiler | /tokenizer.py | 4,866 | 3.53125 | 4 | PRINT, BEGIN, END, IF, THEN, ELSE, \
WHILE, OR, AND, NOT, READ, PROGRAM, \
VAR, INT, BOOLEAN, \
TRUE, FALSE, \
FUNCTION = ('print', 'begin',
'end', 'if', 'then',
'else', 'while',
'or', 'and', 'not', 'read',
'program', 'var', 'int',
... |
e50b83b55d5f3e602cf6ffaef14215925c67ad99 | abmish/pyprograms | /euler/e4.py | 428 | 4.03125 | 4 | """
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99
Find the largest palindrome made from the product of two 3-digit numbers
"""
num = 0
for a in xrange(999, 100, -1):
for b in xrange(a, 100, -1):
prod = a * b
if pr... |
3c4a3dc515cd2b4520c10c95e12a07e5d42ee119 | ddc899/cmpt145 | /Tanner's Docs/A5/a5q2_scoring.py | 8,508 | 3.53125 | 4 | # CMPT 145: Assignment 5 Question 2
# test script
# try to import the student's solutions
imported = False
try:
import a5q2 as student_a5q2
imported = True
except:
print('a5q2 not found')
# if a5q1 isn't there, try A5Q2
if not imported:
try:
import A5Q2 as student_a5q2
print('found A5... |
5a43969531621b3dd525ec892bb43e70387d34e5 | nbenkler/CS110_Intro_CS | /Lab 2/strings3.py | 1,927 | 4.78125 | 5 | '''strings3.py
Blake Howald 9/19/17, modified from original by Jeff Ondich, 2 April 2009
This sample program will introduce you to some standard string
operations. See http://docs.python.org/library/stdtypes.html#id4
for documentation on these operations and many more.
'''
# Using the "replace" method.
... |
bf15be1134f9a189240999810bcc7cd9a717138e | emmas0507/leetcode | /rotate_list.py | 745 | 4.0625 | 4 | class Node(object):
def __init__(self, value, next=None):
self.value = value
self.next = next
def rotate_list(list, K):
length = 0
head = list
while head is not None:
length = length + 1
head = head.next
K = K % length
start = list
end = list
for i in ran... |
5237f812f3f5a863b3b2cd9b421c42a48c8796b0 | nlscng/ubiquitous-octo-robot | /p000/problem-50/BinaryTreeArithmetic.py | 1,761 | 4.21875 | 4 | # Good morning! Here's your coding interview problem for today.
#
# This problem was asked by Microsoft.
#
# Suppose an arithmetic expression is given as a binary tree. Each leaf is an integer and each internal node is one
# of '+', '−', '∗', or '/'.
#
# Given the root to such a tree, write a function to evaluate it.
#... |
091726856e4d4166dbfdb0056da20c7170ddc529 | Dreamh4ck/Projects_2020 | /4.py | 524 | 3.953125 | 4 | def string2ascii(s):
ascii = [ord(c) for c in s]
ascii = int("".join(map(str, ascii)))
return ascii
def checkPrime(number):
if number > 1:
for i in range (2, number//2):
if (number % i) == 0:
print("", number, "is not a prime number")
break
else:
print("", number, "is a prime number")... |
d9401522c65f04972b580897eb3c78c8a5fe637c | csw279/new | /dailywork/020502.py | 279 | 3.65625 | 4 | db={'username':'123','password':'1234'}
x=[]
for i in db:#(for循环取值时虽然是取得元素,但是字典的键值段时分别取出来的,所以直接取得 键 key 当然db.keys()用这个方法也是可以的)
x.append(i)
x.append(db[i])
print(x)
|
94452e87dbcbe59438f56bd162af66d0b21c10fa | gaspard-quenard/artificial_intelligence | /reinforcement_learning/Puzzle/puzzle.py | 11,617 | 3.5625 | 4 | import numpy as np
import matplotlib.pyplot as plt
import itertools
from p5 import *
class Board():
def __init__(self, width, height, width_square):
self.width = width
self.height = height
self.width_square = width_square
self.ending_point = (3, 1)
self.counter = 0
... |
1230865a40b0736f0385ad8d31fe23b578d196e6 | SophieWilson/Snakegame | /snakeclass.py | 8,421 | 3.609375 | 4 |
import pygame, sys, random
from pygame.locals import *
pygame.init()
random.seed()
pygame.display.init()
# size = width, height = 600, 600 #nothing changes if you remove this
screen = pygame.display.set_mode((1280, 700) ,0)
class Megasnakes (pygame.sprite.Sprite):
""" snakes?? """
def __init__(self, x, y):
... |
34f027457836acbfef92f92032b0f0697f788f52 | IlhamLamp/uas-program1 | /program1/model/daftar_nilai.py | 3,274 | 3.609375 | 4 | from view.input_nilai import *
mahasiswa = {}
#menambah daftar mehasiswa
def tambah_data():
global mahasiswa
print("Masukkan data mahasiswa . . .")
nama = input_nama()
nim = input_nim()
n_tugas= input_ntugas()
n_uts = input_nuts()
n_uas = input_nuas()
n_akhir= nakhir(... |
2c74acae8a43f870b39a0614a88f8a548ef65b67 | echase6/network_poker | /client.py | 2,641 | 3.9375 | 4 | """Client main and modules for communicating with server and displaying table.
Run this module on the client computers (i.e., computers for each player)
Hard-coded to work with a fixed address, entered at startup. This can be
changed in the connect_to_server() module.
Valid ports are 8000 and 8001. It is more sta... |
83d372efff8124802bc558a1bb0aab15e0b6a409 | ArnaVin/Python-Games | /Connect4/Connect4_v1.py | 2,123 | 3.515625 | 4 | # Terminal based Connect-4
import numpy as np
ROW_COUNT = 6
COLUMN_COUNT = 7
def create_board():
board = np.zeros((ROW_COUNT, COLUMN_COUNT))
return board
def drop_piece(board, row, col, piece):
board[row][col] = piece
def is_valid_loc(board, col):
return board[ROW_COUNT-1][col] == 0
def get_next... |
53cd61636b7676bcdcb6f8f353fe1b6f134a0cb9 | Floozutter/silly | /python/fizzbuzzfunctional.py | 1,446 | 3.828125 | 4 | """
An extensible solution to the FizzBuzz problem, in a functional style.
https://en.wikipedia.org/wiki/Fizz_buzz
Updated using Maciej Piróg's "FizzBuzz in Haskell by Embedding a
Domain-Specific Language"!
https://themonadreader.files.wordpress.com/2014/04/fizzbuzz.pdf
"""
from functools import reduce
from typing im... |
8fabcc035d501d122253075038f400382ced8b02 | AshimaSEthi/Tkinter_Programs | /Buttons.py | 382 | 3.671875 | 4 | import tkinter as tk
def addition():
a=40
b=50
add_num = a+b
label.configure(text=str(add_num))
root = tk.Tk()
root.title("Buttons in Tkinter")
root.geometry("500x400")
button = tk.Button(root,text="Add Button",command=addition)
button.pack(padx=20,pady=20)
label = tk.Label(root,text="Hi ! I am... |
43c8e84326c18d4e902dce3b62b4d24d3674db14 | rinleit/hackerrank-solutions | /problem-solving/Implementation/The Time in Words/solutions.py | 1,530 | 3.546875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the timeInWords function below.
def timeInWords(h, m):
hours = ("", "one", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten",
"eleven", "twelve")
minutes = ... |
a8cd6106047b1bb15bf22351dce5c01c1ed7aec7 | Thomas-Rudge/facebook-birthday-bot | /fb_bday_bot.py | 7,103 | 3.65625 | 4 | #! python3
#-------------------------------------------------------------------------------
# Name: facebook-birthday-bot
# Purpose: Automatically checks your facebook notifications for
# friends birthdays, and writes a message on their wall.
# Author: Thomas Rudge
#
# Created: 5th July... |
8be0717b0ebadb8b59dbdc96ffd18e5db9c4c84d | cvnlab/GLMsingle | /glmsingle/ols/olsmatrix.py | 4,644 | 3.609375 | 4 | import numpy as np
from sklearn.preprocessing import normalize
import scipy.linalg
def olsmatrix_ulen(X, mode=0):
"""
olsmatrix(X, mode, verbose)
<X> is samples x parameters
<mode> (optional) is
0 means normal operation
1 means use inv instead of '\' and omit unit-length normalizatio... |
56acca97e95440e33174419bd98b6f47481bec1e | Ainzll/Python | /Turtle-Code.py | 1,510 | 3.921875 | 4 | #MODULE 7 - Pythin Turtle graphics
#https://docs.python.org/3/library/turtle.html (Links to an external site.)
#Before using turtle install turtle graphics.
#sudo apt install python3-tk python-tk
#
#Try this code:
import turtle
from random import randrange
w = turtle.Screen()
w.clear()
w.bgcolor("#ffffff")
t = turtle.... |
a146fe8f1e56a8c5b6dde11406d57f4f4754ddfe | ayk-dev/python-fundamentals | /lists-advanced/demo_my_map.py | 403 | 4.03125 | 4 | def my_map(function, items):
new_items = []
for item in items:
new_item = function(item)
new_items.append(new_item)
return new_items
strings = ['1', '2', '3', '4', '5']
my_map_result = my_map(lambda string: string + 'hello', strings)
map_result = list(map(lambda string: str... |
5a9f974041a1ef33a97255f89f084099d468fe7f | NikhilBhargav/Joy_Of_Learning_Python | /RockPaperScissor.py | 1,566 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 4 15:27:43 2020
Rock, Paper Scissor game
@author: nikhil1.bhargava
"""
def rockPaperScissor(player1_choice,player2_choice,secretbit_player1,secretbit_player2):
p1=int(player1_choice[secretbit_player1])
p2=int(player2_choice[secretbit_playe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.