blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
dc68b3a0f41f752b188744d0e1b0cdb547682b11 | HYnam/MyPyTutor | /W3_if_vowels.py | 1,070 | 4.5 | 4 | """
If Statements Using Else
In the previous question, we used an if statement to run code when a condition was True. Often, we want to do something if the condition is False as well. We can achieve this using else:
if condition:
code_if_true
[code_if_true...]
else:
code_if_false
... |
d8bdbbf1e4426b928b14400e35938562cffaa83d | zwiktor/Checkio_zadania | /Split_list.py | 676 | 4.25 | 4 | # https://py.checkio.org/en/mission/split-list/
def split_list(items: list) -> list:
half_list = len(items)//2
if len(items) % 2 == 1:
half_list += 1
return [items[:half_list], items[half_list:]]
if __name__ == '__main__':
print("Example:")
print(split_list([1, 2, 3, 4, 5, 6]))
# Th... |
73ae7d6b716b27bbaddb118b54f8bcd0bcf140d3 | ikkaku1005/ML100Days-1 | /訂正/06訂正.py | 597 | 4 | 4 | #1. [簡答題] 請問下列這三種方法有什麼不同?
#print(a.sum())
#print(np.sum(a))
#print(sum(a))
print("sum() 是 python 內建的函式,所有型態皆可以用。np.sum(a) 跟 a.sum() 是陣列專有的函式,差別在於定義在 np 或是 array 底下。")
#2. 請對一個 5x5 的隨機矩陣作正規化的操作。
import numpy as np
A = np.random.random((5,5))
print(A)
A = (A - A.min()) / (A.max()-A.min())
#3. 請建立一個長度等於 10 的正整數向量,並且將其... |
51fd371fd9ac47d70e52b6aa5c8683a43343050c | ikkaku1005/ML100Days-1 | /訂正/07.訂正二.py | 196 | 3.546875 | 4 | import numpy as np
#2. 如何從一個陣列中,找出出現頻率最高的數值與位置?
Z = np.random.randint(0,10,50) #(min,max,size)
print(Z)
rint = (np.bincount(Z).argmax())
print(rint) |
987cddbe66e9c2af2137fa6b09e43338677633ff | ikkaku1005/ML100Days-1 | /訂正/10訂正.py | 3,004 | 4.78125 | 5 | #2. 請根據提供的資料,選擇出下列的要求:
# - select the first 3 rows.
# - select the odd rows. (index = 1, 3, 5)
# - select the last 2 columns.
# - select the even columns. (index = 0, 2, 4)
# 參考解答
# - select the first 3 rows.
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(6,3),columns=['col1','col2','col3'])
p... |
c045a9c941e5dec7b561e977c3182b3a90c2f198 | ikkaku1005/ML100Days-1 | /訂正/09訂正.py | 1,639 | 3.796875 | 4 | # 參考解答:方法二
import pandas as pd
d = [
['Austin', 139, 'Sun'],
['Dallas', 237, 'Sun'],
['Austin', 139, 'Mon'],
['Dallas', 456, 'Mon'],
]
df = pd.DataFrame(d, columns=['city', 'visitor', 'weekday'])
print(df)
# city visitor weekday
#0 Austin 139 Sun
#1 Dallas 237 Sun
#2 Austin ... |
824a3832965ce7048b89c23f4d17b1515e9215c0 | abirqasem/result_processor | /basic_recursion.py | 1,754 | 3.546875 | 4 | import json
def is_simple (var):
'''
returns true if the variable is a simple data
'''
return isinstance(var, (float, int, str))
def get_children (node):
'''
gets the subscript if the node is a list, keys if it is a dictionary
or an empty list if the node is a simple data type
'''
... |
41c961a3247b10e31e8d430a3a9788f50017bac2 | dragly/pbrt-v2 | /vsd/scripts/sprite/sprite_generation.py | 4,780 | 3.796875 | 4 | #!/usr/bin/python
################################################################################
# Copyright BBP/EPFL (c) 2015
# Author : Marwan Abdellah (marwan.abdellah@epfl.ch)
################################################################################
import struct
import random
import os
import sys
import ... |
be25d408f582b7454a795fb81757bf9f3a57aec7 | Eunsoogil/pythonStudy | /basic/oop.py | 4,800 | 3.59375 | 4 | # oop
print('\n------------------------oop-----------------------\n')
print(type(None))
print(type(True))
print(type(5))
# object임
class BigObject:
# code
pass
print(type(BigObject))
objTest = BigObject() # instanciate
print(objTest) # 주소
class PlayerCharacter:
# Class Object Attribute
# stati... |
edb7cb3c4ee6562817d60924828836e66eed9011 | PraveshKunwar/python-calculator | /Volumes/rcc.py | 410 | 4.125 | 4 | import math
def rccCalc():
print("""
Please give me radius and height!
Example: 9 10
9 would be radius and 10 would be height!
""")
takeSplitInput = input().split()
if len(takeSplitInput) > 2 or len(takeSplitInput) < 2:
print("Please give me two numbers only to work with!")
value... |
52aa981f3c04795ebf6a1f1018006a4691ed26df | PraveshKunwar/python-calculator | /Volumes/cube.py | 151 | 3.796875 | 4 | def cube():
print("Please give me length you would like to cube!")
takeInput = input()
cubeValue = int(takeInput) ** 3
print(cubeValue) |
00222eb128ff05f7eeca60d52ea361d5c5bd8a71 | kjin67511/morning-pi | /weather/weather_view.py | 6,847 | 3.765625 | 4 | # -*- coding: utf-8 -*-
import datetime
def python_unichr(chr_code):
"""
compatible function for chr(python 3.x) and unichr(python 2.x)
"""
try:
from builtins import chr
except ImportError:
return unichr(chr_code) # python 2.x
else:
return chr(chr_code) # python 3.x
... |
88a1d6e861ce502cebd336c470c0f9d5b513a10f | kjin67511/morning-pi | /utils/timer.py | 386 | 3.8125 | 4 | import time
def int_time():
return int(time.time())
def timer_list(duration, interval):
"""
reset timer list
main loop will check timer list and pop the head item to consume
:return: list consists of second (0, 30, 60, ... 1800)
"""
count = int(duration / interval)
l = []
for c ... |
7734abe90cf4fc29cea10461aac3869f05587605 | cht9862/python-demon | /hello.py | 1,271 | 4 | 4 | # # # 定义一个人类
# # class Pe():
# # def __init__(self,*name): #魔术方法不用自己调用
# # self.name=name
# # if __name__ == "__main__":
# # print(self.name)
# # def Pe_run():
# # print('正在疯狂的奔跑~~~')
# class Dog():
# #name
# #age
# #gender
# #height
# ... |
418d762c3bae3602959cce001d1cf9d32bae5ae7 | mjanssen2/Casimir-programming | /test.py | 261 | 3.734375 | 4 | import numpy as np
print("Hoi","lekkkkahh")
def surface_area(r):
return np.pi*r**2
def circumference(r):
return 2*np.pi*r
#print("Circumference of circle with radius 1: ", circumference(1))
#print("Surface area of circle with radius 1: ", surface_area(1))
|
32321cdb22a57d52a55354adc67bdf020828a8e1 | nitinaggarwal1986/learnpythonthehardway | /ex20a.py | 1,317 | 4.375 | 4 | # import the argv to call arguments at the script call from sys module.
from sys import argv
# Asking user to pass the file name as an argument.
script, input_file = argv
# To define a function to print the whole file passed into function as
# a parameter f.
def print_all(f):
print f.read()
# To define a rewind fu... |
0bbda345567c790c263dcc3da3abb54cf26c7756 | nitinaggarwal1986/learnpythonthehardway | /ex19a.py | 1,158 | 4.0625 | 4 | # Create a function cheese_and_cracker to mention things about the
# amount of cheese and crackers mentioned by the arguments.
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print "You have %d cheeses!" % cheese_count
print "You have %d boxes of crackers!" % boxes_of_crackers
print "Man that's enough for ... |
9a731a02ef23cf31516ed0f2e79d4aa3fda0f3bc | uzairkhan57/Python_Challenge | /poll_codes.py | 1,572 | 3.515625 | 4 | import os
import csv
#CSV Path
csvpath = Pypollcsv = os.path.join('Resources','election_data.csv')
# Open and read the CSV
with open(csvpath, newline="") as csvfile:
# header
csvreader = csv.reader(csvfile, delimiter=",")
csv_header = next(csvfile)
#Declaring variables
contestants = ... |
cfec38ee4980c43ba81e12f9654d53ec871bcae8 | annablas279/France-IOI | /Lvl-1/02-Répétitions d'instructions/01-Jeu de dames.py | 158 | 4.03125 | 4 | for loop in range(20):
for loop in range(20):
print("OX", end = "")
print()
for loop in range(20):
print("XO", end = "")
print()
|
c3e4e1574fd021b1a0e2d311f935006380316cb1 | adjoint/around_campus | /dijkstra.py | 3,495 | 3.640625 | 4 | import sys
class Edge:
def __init__(self, u, v, length):
self.u = u
self.v = v
self.length = length
def __str__(self):
return "edge (" + str(self.u) + "," + str(self.v) + ")"
class Node:
def __init__(self, ID):
self.ID = ID
self.dist = sys.maxint
... |
8872d33049899b976831cea4e01e8fc73f88ebef | bvsbrk/Learn-Python | /Basics/using_super_keyword.py | 684 | 4.46875 | 4 | class Animal:
name = "animal"
"""
Here animal class have variable name with value animal
Child class that is dog have variable name with value dog
So usually child class overrides super class so from child class
If we see the value of name is dog
To get the value of super class we use 'sup... |
e45591041021dd5b7125429d1e5660285bfc96a1 | bvsbrk/Learn-Python | /Data-Structures/lists/lists.py | 192 | 3.921875 | 4 | from collections import deque
q = deque([])
for i in range(0, 10):
q.append(i)
print(q)
q.popleft()
print(q)
"""deque can be used as stack as well as queue"""
print(q.pop())
print(q)
|
7df4a38d95fb1c271f8e5455ae1b785868cc39f4 | bvsbrk/Learn-Python | /Control Flow/functions.py | 207 | 3.921875 | 4 | def calculate_fib(n):
a, b = 0, 1
l = []
while a < n:
l.append(a)
a, b = b, a + b
return l
a = calculate_fib(int(input('Fibonacci series below ? ')))
print(a)
print(len(a))
|
420f957de2c792aee79e965de82ebc9be4bcf00c | Nisha16/leetcode | /mergeIntervals.py | 1,693 | 3.921875 | 4 | def mergeInterval(intervals):
sorted_by_lower_bound = sorted(intervals, key=lambda tup: tup[0])
merged = []
for higher in sorted_by_lower_bound:
if not merged:
merged.append(higher)
else:
lower = merged[-1]
# test for intersection between lower and h... |
4b052538c3c005db5316d52ef01e14b503b3c0e1 | Nisha16/leetcode | /mergeKsortedlist.py | 1,680 | 3.796875 | 4 | import heapq
def merge(arr):
heap = [(l[0],i,0) for i,l in enumerate(arr) if len(l) > 0]
print heap
heapq.heapify(heap)
lst = []
while heap:
item,lst_index,item_index = heapq.heappop(heap)
print "item: ", item
print 'last index: ' , lst_index
print 'ite index: ', item_index
lst.append(item)
if ite... |
8367953420cc170f989bc28b90e20f9b7e0b7edf | Nisha16/leetcode | /rand7int.py | 527 | 3.6875 | 4 | from random import randint
import random
def rand2():
x = random.randint(0,5)
if x == 4:
return rand2() # restart
else:
return x % 2
def rand7():
x = rand2() * 4 + rand2() * 2 + rand2()
if (x == 7):
return rand7() #restart
else:
return x
print "number is: ", rand7()
cnt = [0 for x in range(7)]
def simul... |
63e0df545301a186f5b724d442f023d4d0cb4f39 | Nisha16/leetcode | /kadane_matrix.py | 1,572 | 3.59375 | 4 | def kadane(array):
max_so_far = 0
max_end_here = 0
#below inputs for matrix sum
current_start = 0
maxStart = -1
maxEnd = 0
allNegative = True
for i in range(len(array)):
max_end_here += array[i]
if max_end_here < 0:
max_end_here = 0
current_start = i+1
if max_so_far < max_end_here:
max_so_far ... |
13050642f380ae521b3396f2598c96e9c9e0d106 | Nisha16/leetcode | /Queue.py | 522 | 3.796875 | 4 | class Queue:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def enqueue(self, item):
self.items.insert(0,item)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
def rear(self):
re... |
117bd55a38c9dd841e5e3f550fc840d650b1deca | koodin9/hackkerrank | /Algorithm/Implemantation/queens-attack-2.py | 2,614 | 3.625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the queensAttack function below.
# def move_queen(n, updated_row, updated_col, r, c, obstacles):
# p = 0
# while True:
# r = updated_row(r)
# c = updated_col(c)
# key = (r - 1) * n + c
# if (c < ... |
e628e8db78e548d5486e8e44cfbd6b6ddf7eb964 | liang2713020/Learning | /Python-learning/时间测量/性能测量_time模块.py | 696 | 3.640625 | 4 | #-------------------------------------------------------------------------------
# Name: 性能度量
# Purpose:
#
# Author: Administrator
#
# Created: 19/02/2014
# Copyright: (c) Administrator 2014
# Licence: <your licence>
#-----------------------------------------------------------------------... |
03e951708fc253fc4d5b9e961b8cb624cd03c7b8 | afauth/mudecay | /MuonDecay/acquisition/SaveOutputs/Add_Parent_Folder.py | 776 | 3.765625 | 4 | import sys, os, inspect
def Add_Parent_Folder():
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir)
Add_Parent_Folder()
print('\n')
for i in range(len(sys.path)):
print(sys.path[i])
print('\n')
... |
2b63c72335de1a17fc89e2fc3e0b51b66ce36b03 | discord-styled/discord-interactions-styled | /discord_styled/utils/slash.py | 4,210 | 3.5 | 4 | from typing import Union
from discord_slash.utils.manage_commands import create_choice, create_option
class Options:
"""Creates a slash command options template
### Example: ::
my_options = Options()
"""
def __init__(self) -> None:
self.options = []
def _prepare_choices... |
075982983b72b0ba06285130e1a0107f4152c548 | ganius/hackerrank | /data_structures/02_linked_lists/02_insert_element_at_the_tail.py | 369 | 4.03125 | 4 | # https://www.hackerrank.com/challenges/insert-a-node-at-the-tail-of-a-linked-list/problem
from .linked_list_common import Node
def insert(head, data):
"""
Recursive insert if there is head, otherwise initialize the head with the given data
"""
if head:
head.next = insert(head.next, data)
... |
85c889b0aef43d5d9919a682b609ea6f54664eaf | Whatsupcory/Practice | /ex11.py | 330 | 3.90625 | 4 | print "How old are you?",
age = raw_input()
print "How tall are you (inches)?",
height = raw_input()
print "How much do you weight (lbs)?",
weight = raw_input()
print "So, you're %r years old, %r inches tall and %r lbs." % (
age, height, weight)
name = raw_input('Enter your name: ')
print ("Hi %s, Let us be friends!... |
7650e9b847b6c8b636cfd8f046880a6e1f154a2c | Votkca/shiyanlou-code | /jump7.py | 218 | 3.6875 | 4 | for a in range(0,11):
for b in range(0,10):
c = 10 * a + b
if a == 7 or b == 7 or c % 7 ==0:
continue
elif c > 100 or c ==0:
break
else:
print(c)
|
bf8f940e3ab226d3fb76122b8d151eb810f09e02 | linkjavier/holbertonschool-machine_learning | /supervised_learning/0x01-classification/5-neuron.py | 3,218 | 4.21875 | 4 | #!/usr/bin/env python3
""" Python program to implement a single neuron neural network """
import numpy as np
class Neuron():
"""
Class Neuron that defines a single neuron
performing binary classification.
"""
def __init__(self, nx):
""" Init method for Neuron Class """
if... |
75c580928ed9085a1e94ec434ff38d9f699ea7ef | linkjavier/holbertonschool-machine_learning | /supervised_learning/0x04-error_analysis/0-create_confusion.py | 496 | 3.703125 | 4 | #!/usr/bin/env python3
""" Create confusion module """
import numpy as np
def create_confusion_matrix(labels, logits):
"""Function that creates a confusion matrix:"""
m, classes = labels.shape
ConfusionMatrix = np.zeros((classes, classes))
for i in range(m):
Indexlabel = labels[i]
In... |
6b25d3be4ddd036a737fa2f4b3d13d1e2e863e69 | linkjavier/holbertonschool-machine_learning | /unsupervised_learning/0x02-hmm/3-forward.py | 1,240 | 3.875 | 4 | #!/usr/bin/env python3
""" The Forward Algorithm """
import numpy as np
def forward(Observation, Emission, Transition, Initial):
""" Function that performs the forward
algorithm for a hidden markov model
"""
if not isinstance(Observation, np.ndarray) or len(Observation.shape) != 1:
retu... |
1b7ae5f1ee7c11a9299de616c22fbaf649cfc9ff | linkjavier/holbertonschool-machine_learning | /unsupervised_learning/0x02-hmm/0-markov_chain.py | 766 | 3.671875 | 4 | #!/usr/bin/env python3
""" Markov Chain """
import numpy as np
def markov_chain(P, s, t=1):
""" Function that determines the probability of a markov chain
being in a particular state after a specified number of iterations
"""
if not isinstance(P, np.ndarray):
return None
if not isins... |
0be930cd7c9b9c39f18ab7be42371ccb18322d2c | linkjavier/holbertonschool-machine_learning | /pipeline/0x01-apis/4-rocket_frequency.py | 1,044 | 3.65625 | 4 | #!/usr/bin/env python3
""" How many by rocket? """
import requests as rq
if __name__ == '__main__':
""" Script that displays the number of launches per rocket """
launchesUrl = "https://api.spacexdata.com/v4/launches"
launchesRequest = rq.get(launchesUrl)
launches = {}
for launch in launchesReq... |
d4d168e6e4b9794a564c71a43c294563304d47c8 | linkjavier/holbertonschool-machine_learning | /supervised_learning/0x09-transfer_learning/0-transfer.py | 2,110 | 3.59375 | 4 | #!/usr/bin/env python3
""" 0x09. Transfer Learning """
import tensorflow as tf
import tensorflow.keras as K
# Load CIFAR10 Data
(X_train, Y_train), (X_test, Y_test) = K.datasets.cifar10.load_data()
def preprocess_data(X, Y):
"""
Script that trains a convolutional neural network
to classify the ... |
eb78ed07fcecffd9e415d3d531d26b01da67551d | LeOneMoe/mergeSort | /mergeSort.py | 1,379 | 4.0625 | 4 | def merge (left, right, array, reverse):
l = 0
r = 0
a = 0
if reverse:
while l < len(left) and r < len(right):
if left[l] > right[r]:
array[a] = left[l]
l += 1
else:
array[a] = right[r]
r += 1
... |
60ff8f4f8525f21b9481630dbc36d4954c8d3bbe | eazapata/python | /Ejercicios python/PE6/PE6E1.py | 243 | 4.03125 | 4 | #P6E1
#introducir palabras, simplemente pulsa Enter.
#El programa termina escribiendo la lista de palabras.
lista1=[]
pal=input("Escribe una palabra\n")
while pal !="":
lista1+=[pal]
pal=input("Escribe otra palabra\n")
print(lista1)
|
9b9a3cc0ceb807373aa9c542ba8f3de0a28436e6 | eazapata/python | /Ejercicios python/PE5/PE5E10.py | 288 | 4.1875 | 4 | #Escribe un programa que pida la altura de un
#triángulo y lo dibuje de la siguiente
#manera:
alt=int(input("Introduce la altura del triangulo\n"))
simb=("*")
for i in range (alt):
print (" "*(alt-1)+simb)
simb=simb+"**"
alt=alt-1
|
25a783a55ac2fbfa3d69ac9afe12e71298ec95cc | eazapata/python | /Ejercicios python/PE5/PE5E4.py | 265 | 4.03125 | 4 | #PE5E4 Eduardo Antonio Zapata Valero
#Escribe un programa que pida un número y calcule su factorial.
num=int(input("Introduce el número del que quieres sacar el factoria\n"))
factorial=1
for i in range(1,num+1):
factorial=i*factorial
print("El factorial de",num,"es",factorial)
|
0a81afd1bccfde119b3571c2a5ba4395ebb7b44f | eazapata/python | /Ejercicios python/PE4/PE4E3.py | 644 | 4.03125 | 4 | #PE4E3 Eduardo Antonio Zapata Valero
#Pida al usuario si quiere calcular el área de un triángulo o un cuadrado,
#y pida los datos según que caso y muestre el resultado.
fig=(input("Quieres calcular el área de un triángulo (t) o de un cuadrado (c) "))
if (fig=="t"):
print ("Ha elegido triángulo, introduce base y alt... |
51813690215f9869258a0ac34795e9b0d6decc86 | eazapata/python | /Ejercicios python/PE2/PE2E4.py | 283 | 3.9375 | 4 | #PE1E4 Eduardo Antonio Zapata Valero
#Calcular el mayor de dos números
print ("Introduce los números que quieres comprobar ")
num1=float(input())
num2=float(input())
if num1>num2:
print("El mayor es ", num1)
elif num1<num2:
print("EL mayor es ", num2)
else:
print("Los números son iguales")
|
944f4e0537116c251501666e9354601246e750a6 | eazapata/python | /Ejercicios python/PE6/PE6E2.py | 345 | 4.09375 | 4 | #P6E2
#Escribe un programa que te pida números y los guarde en una lista.
#Para terminar de introducir número, simplemente escribe “Salir”.
#El programa termina escribiendo la lista de números.
lista=[]
num=int(input("Introduce un número\n"))
while num!="salir":
lista+=[num]
num=input(("Introduce otro número\n"... |
4f234fa719bf8da1069ba26f11471db22b70c434 | eazapata/python | /Ejercicios python/PE2/PE2E2.py | 239 | 3.953125 | 4 | #PE1E2 Eduardo Antonio Zapata Valero
#Convertir grados centigrados en grados Fahrenheit
print("Introduzca los grados que quiere convertir a Fhrenheit ")
c=float(input("Grados centigrados "))
print ("La temperatura en grados Fahrenheit es \n",float (c*(9/5)+32))
|
3f1acbf6364e910ce9564aaf6fd2e8319fc21306 | kalilinukx/frontendMasters | /python_dsa/recursive_binary.py | 1,009 | 4.03125 | 4 | def recursiveBinary(list , target):
# print(len(list))
# print(list)
if len(list) == 0:
# print(len(list))
return False
else:
midpoint = (len(list)) // 2
if list[midpoint] == target:
return True
else:
if list[midpoi... |
27c1c92570484a9f781f4d6db6eabfa033b5c674 | asherhe/nand2tetris-projects | /07/programFiles/VM.py | 8,804 | 3.6875 | 4 | import os
def removeAll(inputList, sub):
'''
Removes all occurances of substring sub in inputList
'''
out = []
for thing in inputList:
out.append(thing.replace(sub, ''))
return out
class Parser(object):
'''
The Parser module of the VM translator
'''
def... |
7ae4858f192bbbc1540e1fb3d8a3831e6a04f6e9 | CodeItISR/Python | /Youtube/data_types.py | 979 | 4.59375 | 5 | # KEY : VALUE - to get a value need to access it like a list with the key
# key can be string or int or float, but it need to be uniqe
# Creating an dictionary
dictionary = {1: 2 ,"B": "hello" , "C" : 5.2}
# Adding a Key "D" with value awesome
dictionary["D"] = "awesome"
print(dictionary["D"])
# Print the dictionary ... |
f455d623bff1631a0776ba00e619dfec79b9d354 | dkaushik95/learn_python | /37.py | 164 | 3.625 | 4 | student = {
'jhon': 86.5,
'jack': 91.2,
'jill': 84.5,
'Harry': 72.1,
'Joe': 80.5
}
print student
print sorted
print sorted(student), sorted(student.values())
|
7e8a435cd03f866e7bdf19c155fde6028c120934 | dkaushik95/learn_python | /7.py | 115 | 3.65625 | 4 | x=2
y=3
print ('X is %d'%x)
print ('Y is %d'%y)
print('swapping')
x,y = y,x
print ('X is %d'%x)
print ('Y is %d'%y) |
a6b4b50f6037a6b686ae37dd92d346dab192e30a | luye-huang/pythonAlg | /hashtable/990.py | 1,408 | 3.828125 | 4 | from typing import List
class Solution:
@staticmethod
def merge(a, b, parents, depth):
a = Solution.getRoot(Solution, a, parents)
b = Solution.getRoot(Solution, b, parents)
if a != b:
if depth[a] <= depth[b]:
parents[a] = b
depth[a] = depth[b... |
5db53aafa70d71cf999cd385c6a5daed89749f80 | ctsit/mdat | /mdat/__main__.py | 3,911 | 3.65625 | 4 | import json
import sys
import argparse
from core import BestAlternative
import csv
__author__ = 'pbc'
def main():
'''
A class to determine the best alternative given a matrix of labeled alternatives and labeled criteria.
Input
-----
Input data can be in the form of a JSON string with this struct... |
12125ef19ef78609863a7589a852f3b5fbf5af39 | Honny1/School_Programing_Python | /kamen_nuzky_papir.py | 499 | 3.671875 | 4 | import random
print("1 - kamen, 2 - nuzky, 3 - papir")
aůersgjsrt=int(input("zadej svoji volbu:"))
asdfzusehrf= random.randint(1, 3)
if (aůersgjsrt==1 and asdfzusehrf==3):
print("lose")
elif(aůersgjsrt==2 and asdfzusehrf==1):
print("lose")
elif(aůersgjsrt==3 and asdfzusehrf==2):
print("lose")
elif(asdfzuseh... |
417c91c72f4b88355ac0530dd38c984995eb93af | Honny1/School_Programing_Python | /p31a.py | 145 | 3.6875 | 4 | #Jan rodak
s=0
print("zadej cislo")
y=int(input("zadej cislo:"))
while(y!=0):
y=int(input("zadej cislo:"))
s=s+1
print("pocet cisel je:",s)
|
b71520891f799c8dbfcf81fbc3c2474785c87cb2 | Honny1/School_Programing_Python | /p3.py | 479 | 3.6875 | 4 | #OBDELNIK
#Jan Rodk
print("++++++++program obdelnik obvod+++++++++++")
input()
a=int(input("zadej delku: ")) # z retezce pretypuje na cislo
b=int(input("zadej sirku: "))
obvod=2*(a+b)
print("obvod obdelnika je: ",obvod)
input()
print("++++++++program obdelnik obsah+++++++++++")
input() ... |
b9e4625f7556e77c1ad3e5ce813cd097e8e28704 | Honny1/School_Programing_Python | /P93.py | 343 | 3.75 | 4 | import math
def delka(x, x1, y, y1):
a= ((x-x1)**2)+((y-y1)**2)
math.sqrt(a)
return a
x=int(input("zadej souadnici x bodu 1: "))
x1=int(input("zadej souadnici y bodu 1: "))
y=int(input("zadej souadnici x bodu 2: "))
y1=int(input("zadej souadnici y bodu 2: "))
a=delka(x, y, x1, y1)
print("vzdlenost bod od s... |
c48263b50ed7f0858fc3945b6c2f126f883988cc | Honny1/School_Programing_Python | /p6 (nabítka).py | 357 | 3.78125 | 4 | #Jan Rodk
#obsah+obvod kruhu /w nabitka
import math
print("obsah+obvod kruhu")
print("O obsah")
print("S obvod")
x=input("vyber operaci : ")
r=int(input("zadej polomr: "))
if((r>0)and(x=="O")):
print("obsah: ",math.pi*r**2)
elif ((r>0)and(x=="S")):
print("obvod: ",2*math.pi*r)
else:
print("chybn zada... |
8be256f47fb1a2ae8a664832321b8948cefd7b02 | Honny1/School_Programing_Python | /p11.py | 190 | 3.78125 | 4 | #IF ELS
#rodak jan
print("sud lich")
x=int(input("zadej slo: "))
if (x%2==0):
print("slo", x," je sud ")
else :
print("slo", x," je lich ")
input()
|
1ecace437fdd01ed381e1828e600416ebe03af55 | Honny1/School_Programing_Python | /P50.py | 2,916 | 3.765625 | 4 | #Jan Rodak
l=0
p=1
df=0
o="y"
op1="y"
op2="y"
op3="y"
heslo="111"
h=input("zadej heslo:")
while(h!=heslo):
print("spatne heslo")
p=p+1
if(p==3):
break
h=input("zadej znovu heslo:")
else:
while(o=="y"):
l=0
p=1
df=0
... |
6f040cb256208d842d3bf4bee6814acae4bdcacc | antunesleo/tic-tac-toe-ai | /ai_services.py | 1,064 | 3.5625 | 4 | from math import inf as infinity
class MinimaxService(object):
@classmethod
def minimax_tic_tac_toe(cls, simulation_match, depth, marker_value):
if marker_value == 1:
best = [-1, -1, -infinity]
else:
best = [-1, -1, +infinity]
if depth == 0... |
4e30ab94d793eea514cdeaf03b3e650616feaebc | mathLab/GRAPE | /grape/utils.py | 536 | 3.578125 | 4 | """Utility functions module"""
def chunk_it(elements, n_procs):
"""
Divide elements in chunks according to number of processes.
:param list elements: list of elements to be divided in chunks
:param int n_procs: number of available processes
:return: list of elements to be assigned to every proc... |
ad957c06c25e302222df9ece239f00915da48ccd | skywalker221-Minsoo/Python-start | /basic/collection/딕셔너리2.py | 281 | 3.84375 | 4 | place = dict()
place['좋아하는 장소'] = '인천'
place['싫어하는 장소'] = '강릉'
print(place['좋아하는 장소'])
print(place)
place['좋아하는 장소'] = '신촌'
print(place.keys())
print(place.values())
for x in place:
print(x, place[x])
|
658a29508e2e62f986cca5c2d5b49d09416c4710 | adipali2016/Python_Hackerrank_Solutions | /24.py | 568 | 3.53125 | 4 | def print_rangoli(size):
# your code goes here
x = list()
l = size
for i in range(0,l):
s = ""
t = 2*i+1
if l <= size:
for j in range(0,t):
if j <= (t/2):
s += chr(ord('a')+(l-j-1)) + '-'
else:
s ... |
0b35571bb85270751838dfd304088dda6ff0c7bf | aletcherhartman/pong.py | /pong.py | 5,335 | 3.609375 | 4 | import pygame
from paddle import Paddle
from ball import Ball
def end(ball,paddleL,scoreR, scoreL,screen):
BLACK = (0, 0, 0)
ball.changeX = 0
ball.changeY = 0
font = pygame.font.SysFont('Calibri', 25, False, False)
text = font.render( "Click to Play Again".format(scoreR, scoreL), True, BLACK)
... |
ba15ee6a1adb80f75b8c446f3b2902ed8ab7c2df | CPernatozzi/Avasia | /Avasia/Cataracta/Fishing.py | 3,197 | 3.515625 | 4 | from Avasia.Logic.util import *
import Avasia.Logic.config as config
import Avasia.Logic.Item_Storage as Item_Storage
from random import randint
from Avasia.Room.Room import Room
def fishing():
print()
print(">>>Fishing<<<")
print()
print("You see the rippling water surrounding you.")
print("You f... |
e854edcaf00511b1631361b419f57c9629a9a029 | shmatov-nikolai/Chapter_4_task_14 | /task_14.py | 516 | 3.640625 | 4 | """
14)Recursion: Davis Staircase(LRU cache)
https://www.hackerrank.com/challenges/ctci-recursive-staircase/problem
"""
s = int(input().strip())
dict_stair = {1:1, 2:2, 3:4}
def recurs_stair(n):
if n in dict_stair.keys():
return dict_stair[n]
else:
dict_stair[n] = (recurs_stair(n-1)+ recurs_st... |
8370f455f7add6ed418333af6d0eda1243ad222c | abhimanyusahai/predictive-analytics | /machine learning-coursera-andrew-ng/week-7-svm-practice.py | 5,895 | 4.03125 | 4 | # This Python 2.7 code implements the first part of the programming assignment from Week 7 of Andrew Ng's course on Machine Learning
# on Coursera. It demonstrates how to build Support Vector Machines in Python using both Linear and Gaussian kernels.
# It uses the numpy, pandas, scipy, matplotlib and an off-the-shelf m... |
6e3be6d094159a0f9f2c4a37754c9cba40e51349 | irynakravchenko/test_ivk | /Homework_3.py | 1,416 | 4.03125 | 4 | #1
s=input("Введите строку:")
print('3 символ:', s[2])
print('предпоследний символ:', s[-2])
print('первые пять символов', s[0:5])
print('кроме двух последних:', s[:-2])
print('символы c четным индексом:', s[0::2])
print('символы c нечетным индексом:', s[1::2])
print('символы в ообратном порядке:', s[::-1])
print('симв... |
73c28455d84b9c175be5d8b9d3517dd80a1a4ab8 | Jason-Cee/Python-Recursion | /Task.py | 312 | 3.765625 | 4 | # Task 1
# First 20 fibonacci numbers
# Define function
def fib(a):
# Stops parameter from being less than 1
if a <= 1:
return a
else:
# Fibonacci calculation
return fib(a - 1) + fib(a - 2)
# Range to allow loop 20 times
for i in range(20):
print(str(fib(i)), end=" ")
|
056f765a7ae81f05411c3760e0945e6642e75bac | kris-gaudel/project-euler | /10001stPrime.py | 385 | 3.859375 | 4 | # Prime generator
def GeneratePrime(number):
count = 1
num = 1
while (count < number):
num += 2
if PrimeTest(num):
count += 1
return num
# Prime tester
def PrimeTest(a):
factor = 2
while (factor * factor <= a):
if a % factor == 0:
return False
... |
83f798a39bc65fa84d9349984497afa36bc4d139 | callmemaze/GamePlayground | /Game/rpsls.py | 1,522 | 3.875 | 4 | # Rock-paper-scissors-lizard-Spock template
# 0 - rock
# 1 - Spock
# 2 - paper
# 3 - lizard
# 4 - scissors
import random
#Converts name to numnber
def nameToNumber(name):
pass
if name=="rock":
return 0
elif name=="Spock":
return 1
elif name=="paper":
return 2
elif name=="l... |
6484cd91c46ec62aa1785b5c6f4cdcbb865dec46 | gdc2016/algorithm011-class02 | /Week_03/236.二叉树的最近公共祖先.py | 972 | 3.640625 | 4 | #
# @lc app=leetcode.cn id=236 lang=python3
#
# [236] 二叉树的最近公共祖先
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: ... |
28b8b9d37da2b9cc7f48945726b5ca841bff05ef | JayJayBinks1/Divide-Conquer | /Task3.py | 10,220 | 3.921875 | 4 | import sys
class Bed:
"""
Class representing beds. Stores its name, length and width along with its
compatibility.
"""
def __init__(self, name, x, y):
self.name = name
self.x = x
self.y = y
self.persons_compatible = 0
def get_name(self):
return self.na... |
c516c6e8c6fc7cff25869a8ab57a174c473aa84c | yanviegas/small_codes_2 | /teste_1e2_classe_triangulo.py | 869 | 3.578125 | 4 | class Triangulo:
def __init__ (self, a, b, c):
self.a = a
self.b = b
self.c = c
def perimetro(self):
return self.a + self.b + self.c
def tipo_lado(self):
if self.a == self.b and self.b == self.c:
tipo = 'equilátero'
elif self.a == self.b or self.b == self.c or self.a == self.c:
tip... |
872ba12eaabf793d448b2c0e36b9dc953cddb139 | scidam/algos | /algorithms/intervieweing.io/given_sum.py | 312 | 3.875 | 4 |
# Find pair with given sum in array
#
arr = [1,3,5,8,19]
s = 11
def find_pair(arr, s):
dct = dict()
for item in arr:
dct.update({s-item: item})
for el in arr:
val = dct.get(el, None)
if val:
return el, val
return None
print("Pair is ", find_pair(arr, s))
|
475fe0c425bd46ed406d2ce6492b2b0c0768d7c6 | scidam/algos | /algorithms/intervieweing.io/max_prod.py | 580 | 4.125 | 4 | # find maximum product of two integers in array
#
arr = [-1, 4, 9, -10, -8]
def max_prod(arr):
""" Find maximum product of 2 ints """
fmax = smax = fmin = smin = arr[0]
for k in range(len(arr)):
if arr[k] > fmax:
fmax = arr[k]
if arr[k] < fmin:
fmin = arr[k]
... |
4c8aaf045dae040ed39b071d4e054765b7dfd3f5 | scidam/algos | /algorithms/intervieweing.io/shuffle_fy.py | 324 | 4.21875 | 4 | # Shuffle input array using Fisher-Yates algorithm
import random
arr = list(range(10))
def shuffle(arr):
n = len(arr)
for j in range(len(arr)-1):
i = random.randint(0, j)
arr[i], arr[j] = arr[j], arr[i]
return arr
print("Before shuffling: ", arr)
print("After shuffling: ", shuffle(a... |
2018cbe1902f22a10d56c2d1aca7989f497b8721 | scidam/algos | /algorithms/intervieweing.io/minsumsubarr.py | 473 | 3.5625 | 4 | # Find subarray of a given size and having minimum sum of elements
arr = [1,4,2,6,7,3,1,2,2,3]
size = 3
def find_min(arr, size=size):
ss = sum(arr[:size])
i = 0
j = size - 1
mem = (i, j)
while j < len(arr) - 1:
j += 1
i += 1
probe = ss - arr[i - 1] + arr[j]
print(s... |
21640e950daf8157fab2dec2d055475740d2f509 | scidam/algos | /algorithms/intervieweing.io/longest_subs.py | 606 | 3.9375 | 4 |
# Longest increasing subsequence (contigouos)
arr = [2, 6, 3, 4, 1, 2, 9, 5, 8]
def longest_subs(arr):
current_subs = list()
longest_subs = list()
for k in range(len(arr) - 1):
if arr[k] <= arr[k + 1]:
if k not in current_subs:
current_subs.append(k)
if k ... |
1cce41616b770c1cc4b86cca13bad4db3a20ee95 | scidam/algos | /algorithms/intervieweing.io/majority.py | 448 | 4.03125 | 4 | arr = [1,2,1,2,3,2,4,2,3,2,2]
def find_majority(arr):
"""Boyer-Moore algorithm"""
major = None
counter = 0
for el in arr:
print("Major element: ", major, "Current element: ", el)
if counter == 0:
major = el
counter += 1
elif el == major:
cou... |
a1c2a407f9e3c3bac070a84390674c519ca8ed63 | scidam/algos | /algorithms/sorting/bubble.py | 1,446 | 4.21875 | 4 | __author__ = "Dmitry E. Kislov"
__created__ = "29.06.2018"
__email__ = "kislov@easydan.com"
def bubble_sort(array, order='asc'):
"""Bubble sorting algorithm.
This is a bit smart implementation of the bubble sorting algoritm.
It stops if obtained sequence is already ordered.
**Parameters**
:... |
3d4f2c0e283d492aef64578a2e3fb3ebf24bf42f | SakshamMalik99/Python-Mastery | /List/List5.py | 973 | 4.15625 | 4 | print("Program :5 :")
# *number : number of time List.
list1 = [1, 3, 5]
print(list1*2)
list1 = ['Data Structure', 'C', 'C++', 'Java', 'Unix',
'DBMS', 'Python', 'SQL', 'IBM', 'Microsoft', 'Apple']
print("Orignal list is ", list1)
for data in list1:
print(data)
list1 = [1, 3, 5, 7, 17, 9, 19, 7... |
2d08bf3376d0582b1a266c88564fb0eb3fffdaff | rumihsieh/password-retry | /猜數字小遊戲.py | 298 | 3.703125 | 4 | r = random. randint(1,100)
count = 0
while True:
count = count + 1
num = input('請猜數字:')
num = int(num)
if num == r:
print('恭喜你猜對了!')
break
elif num > r:
print('比他小一點')
elif num < r:
print('比他大一點')
print('這是你猜的第',count, '次')
|
e1369e2118fcab1b6032c8adbf49feac51c0d79c | MrMebelMan/pyvat | /pyvat/xml_utils.py | 973 | 3.65625 | 4 | class NodeNotFoundError(Exception):
"""XML node was not found.
"""
pass
def get_first_child_element(node, tag_name):
"""Get the first child element node with a given tag name.
:param node: Parent node.
:type node: xml.dom.Node
:returns: the first child element node with the given tag nam... |
30cf241927d7fb24f62b6ec3afd4952e05d01032 | KrisztianS/pallida-basic-exam-trial | /namefromemail/name_from_email.py | 512 | 4.40625 | 4 | # Create a function that takes email address as input in the following format:
# firstName.lastName@exam.com
# and returns a string that represents the user name in the following format:
# last_name first_name
# example: "elek.viz@exam.com" for this input the output should be: "Viz Elek"
# accents does not matter
emai... |
983d88e45d890fe904d468452b94e4ac8fb61376 | eagleschool/calculator | /calculator.py | 369 | 3.9375 | 4 | # expirement with python
num1 = input('Enter First Number: ')
num2 = input('Enter Second Number: ')
result1 = float(num1) + float(num2)
result2 = float(num1) - float(num2)
result3 = float(num1) * float(num2)
result4 = float(num1) / float(num2)
print('Addition: ', result1)
print('Subtraction: ',result2)
print('Multipl... |
2a77729a40ce400d81904630658c144d53b86167 | adeen-s/AdventOfCode-2017 | /day4-2.py | 481 | 3.65625 | 4 | passphrases = []
valid = 0
anagrams = 0
while True:
passphrase = input()
if passphrase:
passphrases.append(passphrase)
else:
break
for passphrase in passphrases:
anagrams = 0
li = [s for s in passphrase.split()]
if len(li) != len(set(li)):
continue
for s in li:
... |
0a32c15fce2b63128dea5d429830764e3c622685 | wy/ProjectEuler | /solutions/problem5.py | 1,508 | 3.671875 | 4 | # coding: utf8
# Author: Wing Yung Chan (~wy)
# Date: 2017
def isPrime(n):
#Prime if 2..n-1 does not divide n
for i in range(2,n):
if n % i == 0:
return False
return True
def primes(n):
#returns primes from 2..n
arr = []
for i in range(2,n+1):
if isPrime(i):
... |
7fdd534cced3c8592634771b21c8c1b55bb71cc0 | wy/ProjectEuler | /solutions/problem4.py | 790 | 3.609375 | 4 | # coding: utf8
# Author: Wing Yung Chan (~wy)
# Date: 2017
def palindrome(n):
j = str(n)
for i in range(len(j)//2):
if j[i] != j[len(j)-1-i]:
return False
return True
def problem4():
# Try all 3 digit pairs
# Got to be careful with how you iterate
# Need to create a Zig... |
e97add39ff4f9900685eb58c9a58211bef4c22fd | wy/ProjectEuler | /solutions/problem15.py | 659 | 3.84375 | 4 | # coding: utf8
# Author: Wing Yung Chan (~wy)
# Date: 2017
# Lattice Paths
# Fairly Interesting problem
size = 20
memory = {}
def latticex(i,j):
x = memory.get(str(i)+","+str(j))
if x is None:
y = lattice(i,j,0)
memory[str(i)+","+str(j)] = y
return y
else:
return int(x)
... |
51f4f219eeb2494fd5d5c7ec8a797139e75d00ae | wy/ProjectEuler | /solutions/problem1.py | 265 | 3.828125 | 4 | # coding: utf8
# Author: Wing Yung Chan (~wy)
# Date: 2017
def problem1():
# Check for divisors of 3 or 5, add to accumulator if so
acc = 0
for i in range(1,1000):
if i % 3 == 0 or i % 5 == 0:
acc = acc + i
return acc
print(problem1()) |
dcdf64217dc6a8ef6069f0088d0407a8cf5f6494 | amitzoo/seminnar | /merge_2.py | 3,737 | 3.78125 | 4 | import functools
from functools import partial
from multiprocessing import Process, Pipe, Value, Pool, Queue
import threading
import multiprocessing
import random, time
# Python program for implementation of MergeSort
def mergeSort2(arr):
if len(arr) > 1:
mid = len(arr) // 2 # Finding the mi... |
a34c976901376d241b1f2532ce4393425b848709 | NazarKharchuk/LabsPython | /Laba2 Python.py | 893 | 4.09375 | 4 | a = float(input('Add rib a brick :')) #Ребро a цеглини
b = float(input('Add rib b brick :')) #Ребро b цеглини
c = float(input('Add rib c brick :')) #Ребро c цеглини
if (a > 0 and b > 0 and c > 0):
x = float(input('Enter size x hole :')) #Розмір x отвору
y = float(input('Enter size y hole :')) #Розмір... |
80236630bcd5b6200f919d887283c0c2274fb92c | MarioMatheus/InteligenciaComputacional | /MissionarioseCanibais/State.py | 2,143 | 3.609375 | 4 | # Constants for represent the shore
LEFT = 0 # Left Shore
RIGHT = 1 # Right Shore
class State:
def __init__(self, missionaries=(3,0), cannibals=(3,0), boat='left'):
self.missionaries = missionaries
self.cannibals = cannibals
self.boat = boat
def __str__(self):
return ("\nState:\n"
" Miss... |
6053566d86f72f2400f74883566705c33be69c38 | lshen1120/leetcode | /24.py | 722 | 3.75 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def swapPairs(self, head):
node = head
result = head
prev = None
while node and node.next:
left = node
... |
b89f73076eb3469cd46d4d118a19c8407bfd974c | GianMewes/SciFiPi | /src/SciFiPi/helper/yes_no.py | 244 | 3.890625 | 4 | def yes_no(answer):
yes = set(['y'])
no = set(['n'])
while True:
choice = input(answer).lower()
if choice in yes:
return True
elif choice in no:
return False
else:
print("Please respond with 'y' or 'n' ") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.