blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
20dc08c13c398410c6f876b9ac2d517d496b6cc9 | AShoom85/MyPythonCode | /L8/8_2lambda.py | 2,408 | 3.78125 | 4 | # Exercise 3
# список представляет собой базу данных.
# каждый элемент содержит сведения:
# имя
# возраст
# рост
# вес
# Пользователь может заказать сортировку по любому полю:
# a = [['tom',2,13,3], ['basil',11,15,5],['kity',9,14,4],['soly',4,12,2]]
# n = input('Сортировать по имени (1), возрасту (2), росту (3), весу (... |
e0b23f083be55a84117e6d263bbe5f250d89b906 | Microshak/iotil-sawyer | /sawyer_demo/src/Old/Deleteme.py | 801 | 3.625 | 4 | import speech_recognition as sr
r = sr.Recognizer()
m = sr.Microphone()
#set threhold level
with m as source: r.adjust_for_ambient_noise(source)
print "Set minimum energy threshold to {}".format(r.energy_threshold)
# obtain audio from the microphone
with sr.Microphone() as source:
print "Say something!"
audio ... |
4a455a43e0f61f6bdb41ed33d2c5840d29f078ed | Littlegaga666/VigenereCipher | /py/encrypt.py | 383 | 3.53125 | 4 | def encrypt(initial, key):
""" Use : encrypt("MESSAGEINCAPITALS", "keyword")
=> 'COWUUDNYXGCJFCQVW'
"""
initial = initial.upper()
key = key.lower()
lkey = len(key)
list1 = [ord(i) for i in key]
list2 = [ord(i) for i in initial]
output = ''
for i in range(len(list2)):
value = (list2[i] + list1[i ... |
385717a171ba5d6da57026ea455ddcaf121f98ce | chandana24shetty/mulesoft | /muleSoft.py | 1,821 | 4.375 | 4 | import sqlite3
#Creating a connectrion object for DB
dbname="Movies.db"
connect=sqlite3.connect(dbname)
cursor=connect.cursor()
def createTable():
stmt=" CREATE TABLE IF NOT EXISTS Movies (actor text, actress text, year integer, director text) "
cursor.execute(stmt)
connect.commit()
pri... |
66515922902e95a76c8a40deeedece074127e2c1 | Rjt17/Python | /hackfest 2020 oct/cyclic_binary_string.0.4.py | 597 | 3.75 | 4 | binary_s = str(input())
temp_binary_list = list(binary_s)
temp_binary = binary_s
length = len(binary_s)
decimals = []
decimal = 0
greatest_pow = 0
powers = []
for x in range(len(binary_s)):
temp_binary = temp_binary[1:] + temp_binary[0]
decimals.append(int(temp_binary, 2))
decimals.sort()
print(len(decimals))
decim... |
9023dd0c1287e10a55c2c52b370dbab3297060fa | brianchiang-tw/leetcode | /No_0336_Palindrome Pairs/palindrome_pairs_by_bipartite_partition.py | 3,197 | 4.03125 | 4 | '''
Description:
Given a list of unique words, find all pairs of distinct indices (i, j) in the given list, so that the concatenation of the two words, i.e. words[i] + words[j] is a palindrome.
Example 1:
Input: ["abcd","dcba","lls","s","sssll"]
Output: [[0,1],[1,0],[3,2],[2,4]]
Explanation: The palindromes are ["... |
91be8399f14f62ca28c6e9ff592ba473596a6759 | WilliamPalmtree/Cyphers | /VinegereCipher.py | 3,073 | 3.625 | 4 | def letterSub(letter, key):
if (ord(letter) < 123 and ord(letter) > 96):
#Lowercase
if (ord(letter) + key > 122):
letter = chr(ord(letter) + key - 26)
elif(ord(letter) + key < 97):
letter = chr(ord(letter) + key + 26)
else:
letter = chr(ord(letter) + key)
elif (ord(letter) > 64 and ord(letter) < 91)... |
0e32f323ea0f8ab8ecd70004d80b607ee318dbb7 | jaychsu/algorithm | /lintcode/668_ones_and_zeroes.py | 2,241 | 3.890625 | 4 | """
optimized space complexity
"""
class Solution:
"""
@param: strs: an array with strings include only 0 and 1
@param: m: An integer
@param: n: An integer
@return: find the maximum number of strings
"""
def findMaxForm(self, strs, m, n):
if not strs:
return 0
""... |
cd32dba1fa6cd62bf144144981da4b544b7ea8d8 | AyeJayTwo/smsAnalyze | /dbCreate.py | 4,781 | 3.75 | 4 | from datetime import date # Needed to translate date to day of week
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import sms
import sqlite3
"""Set up the file to be read"""
with open("test_sms.xml", "r") as filetoberead:
sms_file = filetoberead.readlines()
"""Get rid of header information ... |
83b06eab93ce99b7140cea40c934d7baea62d655 | programmerhardik397/password_generator | /password_generator.py | 1,012 | 4.09375 | 4 | print(f"Hello user!! Welcome to the password generator!!!\n")
print("Firstly,you need to create a new username.")
message0 = input("\nSo enter your first name: ")
mess0 = input("Enter your last name: ")
username = (f"Your username: {message0}_{mess0}")
print(username)
import random
password = []
message2 = input("Ente... |
f687393cb17a6e6d4276f216d9f37d5a661186b1 | annabalan/python-challenges | /Practice-Python/ex-03.py | 513 | 4.3125 | 4 | # Take a list, say for example this one: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] and write a program that prints out all the elements of the list that are less than 5.
numbers = [1, 3, 3, 5, 7, 11, 13, 17, 39]
numbers_2 = []
userinput = int(input("Enter a number: "))
def below_five(numbers):
for number in numbe... |
794ef10d107fb4f4a65a55a44f8ada8272c56fe2 | Fadssd33/Seminario-de-Programacion | /Funciones/TelefonoFuncion.py | 1,379 | 3.9375 | 4 | # Se requiere relizar un programa que facture el uso de un telefono considerando lo siguiente:
# a. Le pedira la captura la tarifa por segundo al usuario
# b. Solicita al usuario la cantidad de comunicaciones que se realizaron
# c. Solicitara al usuario la duracion de cada comunicacion, expresada en horas, minutos y se... |
25286e9eeb01e455fe55e3d819a6a2fe93363cd7 | alyxcsulb/homework3 | /solution-321.py | 350 | 4.1875 | 4 | # Change in cents output
# (Calculate change using fewest number of coins)
change = int(input("Enter amount of change due in cents: "))
print("Your change is: ")
print(change//25, "quarters")
change = change%25
print(change//10, "dimes")
change = change%10
print(change//5, "nickels")
change = change%5
print(change//1,... |
41f75e35154b638de9b25c83bc2fe2b8176f32e8 | anmmoinuddin/Python | /Online Course/Computing in Python III(Data Structure)/CP3-I(String).py | 2,553 | 4.28125 | 4 | ##data Structure
## Interger by value
#----------------------------------------------------------------------
#integer
def addone(aninteger):
aninteger=aninteger+1
print("aninterger:", aninteger)
myinteger=5
print("myinteger before addone:", myinteger)
addone(myinteger)
print("myinteger after addone... |
7466b5a7f5659248bbe47c900e21349aa0a73621 | jaehui327/algorithm | /코딩테스트/200914Line/2.py | 567 | 3.78125 | 4 | def solution(ball, order):
answer = []
for i in range(len(order) - 1, -1, -1):
for j in range(0, i + 1):
if order[j] == ball[0]:
answer.append(ball[0])
ball.pop(0)
order.pop(j)
break
elif order[j] == ball[-1]:
... |
04bca0bb6c0de6dd3eea80b16551be76b73b2d8e | Eshliforfriends/itstep | /lesson12/only_odd_arguments.py | 670 | 3.96875 | 4 | def only_odd_arguments(func):
def wrapper_odd(*args):
n = 1
for i in args:
for j in args:
if j % 2 != 0:
if n < len(args):
n += 1
continue
elif n == len(args):
... |
2ce19d9ac8c727e4cd19470d0f9559159de78464 | kgmonisha/PythonScripts | /Numbers/random2.py | 298 | 3.609375 | 4 | import random
import string
moves = ["rock","paper","scissors"]
print(random.choice(moves))
#this will run choice 10 times
print(random.choices(moves, k=10))
#lets assume we have weights for diff colours
wheel = ['red','green','blue']
weights = [10,10,2]
print(random.choices(wheel,weights,k=10))
|
a861c643850a08f6b5c201460f586af9f30a2f5f | kynthus/htnpython | /src/eff_07.py | 637 | 3.78125 | 4 | # -*- coding: utf-8 -*-
R"""
リスト関連の組み込み関数
"""
nums = [1, 2, 3, 4, 5]
# map関数で変換
print(list(map(lambda n: n + 10, nums))) # [[11, 12, 13, 14, 15]
# filter関数で抽出
print(list(filter(lambda n: n % 2 == 0, nums))) # [2, 4]
'''
1000万回繰り返して測定
Python 2系, 3系双方で以下のような結果となった
リスト内包表記
time = 9.73599982262
map関数
time = 13.3900... |
ce1b86bc3798cae7fc12420411c2e9850d0e2285 | Sarang-1407/CP-LAB-SEM01 | /CP Lab/CP Lab Test/CP Lab Test A1 long version.py | 820 | 4.125 | 4 | seconds=float(input("Enter the time in seconds:"))
minutes=seconds//60
hours=minutes//60
days=hours//24
years=days//365
if seconds<60:
print("Years=0, Days=0, Hours=0, Minutes=0, Seconds=",seconds)
if (seconds>=60 and seconds<3600):
print("Year=0, Days=0, Hours=0, Minutes=",minutes,"Seconds=", sec... |
237341e360269c81c118f846b3f9587ca0156e6e | rao257/SamplePythonScripts | /hex2int.py | 4,040 | 3.515625 | 4 | #!/usr/bin/python
#Author: Suraj Patil
#Version: 1.0
#Date: 26th March 2014
'''
this file won't execute, you will have to type this all into the python prompt, which is the appropriate way of
doing programming, as it allows the programmer to have an interactive output
output:
0x0800 2048 Internet Protocol version ... |
2ed97fb513d992577d399ce5673fb259469586e5 | AzhariRamadhan/python-cc | /bab-5.py | 3,114 | 4.0625 | 4 | #5-1 Coditional test
car = 'subaru'
print("Is car == 'subaru'? I predict True.")
print(car == 'subaru')
print("\nIs car == 'audi'? i predict False.")
print(car == 'audi')
#5-3 Alien Colors
print('\n5-3 Alien Colors')
alien_color = ['green', 'yellow', 'red']
if 'green' in alien_color:
print("The Player earned 5 ... |
15718a8f86410eeec008be7534b269300d2d8541 | rahuldbhadange/Python | /__Python/__Class and Object/python OOPS material/python OOPS material/26 removing attributes from a class del.py | 1,130 | 4.09375 | 4 | Removing attributes from a class:
Removing attributes from a object:
ex:
del test.a
del t1.b
here del cannot remove/delete an object
del:del is a keyword,which is used to decrease the reference count
of an object
Reference count:No of variables pointing to an object will give th... |
58180395526bdf082716c12a9175d84ca70145cb | AdamZhouSE/pythonHomework | /Code/CodeRecords/2500/60627/299402.py | 72 | 3.5625 | 4 | s = input()
if s=='[3,2,4,1]':
print('[4,2,4,3]')
else:
print(s) |
ade2a61bde172a6c94af422af6b521f72f0f08ce | jfiander/python | /collatz.py | 175 | 3.546875 | 4 | #!/usr/bin/python
import sys
n = 1
while True:
i = n
while i != 1:
if i % 2 == 1:
i = 3 * i + 1
else:
i = i / 2
sys.stdout.write('.')
n = n + 1
|
b24527531c831766b1fe6593c04e20dc97759327 | nagu1417/DemoPyGit | /Poly_DuckTypingExample1.py | 209 | 3.53125 | 4 | class Timing:
def startTime(self):
print("Starts at 9 am")
print("Ends at 7 pm")
class Cricket:
def time(self,time):
time.startTime();
t1=Timing();
c1=Cricket()
c1.time(t1)
|
bc39fbf75d49fd5f9bebb0f448a09769469f10d0 | Obukhova2001/practicum_1 | /task49.py | 1,220 | 4.09375 | 4 | """
Имя проекта: Boring-numpy
Номер версии: 1.0
Имя файла: practicum-1(1-101).py
Автор: 2019 © Д.А.Обухова, Челябинск
Лицензия использования: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru)
Дата создания: 11/11/2020
Дата последней модификации: 11/11/2020
Связанные файлы/пакеты: numpy, ran... |
9b7e278b107e63d141c84efa9cbf2c2ddb50358c | vchatchai/python101 | /exercise401.py | 102 | 4 | 4 |
values = input("Please insert value: ")
for value in values:
print(value*2, end = "")
print() |
101984ba8119b03efe384ec993ca4b89c7a3fd62 | nikhil1699/cracking-the-coding-interview | /python_solutions/chapter_04_trees_and_graphs/problem_04_08_first_common_ancestor.py | 2,148 | 3.90625 | 4 | """
Chapter 04 - Problem 08 - First Common Ancestor
Problem Statement:
Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree.
Avoid storing additional nodes in a data structure. Assume that this tree is not necessarily a binary search tree.
Assume that nodes in the tree do... |
01b33eddbb4ee68e2dcd7bf315b208588745f2d9 | junfeiZTE/pythonCode | /zip_lambda_map.py | 125 | 3.65625 | 4 | a=[1,2,3]
b=[4,5,6]
print(list(zip(a,b)))
fun=lambda x,y:x+y
print(fun(1,2))
print(list(map(fun,[1,2,3],[4,5,6])))
|
cf2e5dba684b43fd01db23597e70ace70b1b4f97 | Avyuktaj/pythonworks | /B using operators.py | 1,900 | 4.40625 | 4 | # i used operators
# i print used
# Python print(). The print() function prints the given object to the standard output device (screen) or to the text stream file
# operators used : arthematic and logical
# true or false statements
# variables used are x,y,a,b,p,q,p,r,m,n
# all the arthematic operators are given belo... |
28bc87eea4deff643ac1c3f873eec99aa5435409 | GURUIFENG9139/WEB2 | /threadingtest.py | 543 | 3.5625 | 4 | #!/usr/bin/python
# coding: utf-8
import threading
import time
'''
hhhhhhhh
'''
class MyThread(threading.Thread):
def run(self):
for i in range(0,5):
#print i
#print self.name
msg = '线程' + self.name + str(i)
print msg
print threading.activeCount()
# 单... |
3440d218f7e041576f5e1b1ba0d0242c62739e85 | froststars/aws-cfn-templates | /cfnutil/cfnutil/mapping.py | 713 | 3.703125 | 4 | # -*- encoding: utf-8 -*-
__author__ = 'kotaimen'
__date__ = '02/06/2017'
import json
import csv
def load_mapping(filename):
"""Load a mapping form JSON file"""
with open(filename) as f:
return json.load(f)
def load_csv_as_mapping(filename, key1, key2, value):
""" Load mapping from a CSV file
... |
68dd823dd261061a4b7fcae6bb23040f3e0afe84 | NicolasLagaillardie/Python | /hearth.py | 298 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 05 09:33:35 2013
@author: Nicolas
"""
import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(-5,5,100)
plt.plot(x,np.sin(x)) # on utilise la fonction sinus de Numpy
plt.ylabel('fonction sinus')
plt.xlabel("l'axe des abcisses")
plt.show() |
4962972263f2740e4c356a8ea2c40c8c2abf171d | StefanoBelli/ia1920 | /binsearch.py | 1,163 | 3.78125 | 4 | # versione iterativa
def binsearch(l, e):
low = 0
high = len(l) - 1
while low <= high:
mid = int(((high + low) / 2))
if e > l[mid]:
low = mid + 1
elif e < l[mid]:
high = mid - 1
else:
return e
return False
# prima versione ... |
72d3de7dc49d3e36a6a8fe11d973e426397a0f8b | mmassom96/IEEE_Xtreme_5.0 | /problem_A.py | 1,501 | 4.3125 | 4 | import numpy
def pearson (x, y):
if (len(x) != len(y)):
# if the two data sets are not of equal length, then Pearson's Correlation Coefficient
# cannot be calculated so the function will end
print("Error: length of set X is not equal to length of set Y.")
return
setLen = l... |
f4391fd8d4fe2cf0aa1cee311f6da8e2c387b8d2 | dionysos1/ISCRIP | /week1/mars.py | 928 | 3.75 | 4 | import math
#gebruiker voert het aantal sol dagen in die hij wil weten in mars dagen
input = int(input("aantal hele dagen in sol: "))
# zet het aantal sol om in mars seconden
# methode 1
# seconds = (input * 35.244) + (input * 60 * 39) + (input * 60 * 60 * 24)
# methode 2
seconds = (input * 86400) * 1.02... |
2bff8bb965aa4e19850b5fac318efdb9a6099b31 | pengjinfu/Python3 | /Python05/07--函数的返回值.py | 504 | 3.5625 | 4 | #!/usr/bin/python3
# -*- coding:utf-8 -*-
# Authour:Dreamer
# Tmie:2018.6.11
# 函数的返回值,就是把函数的执行结束返回出来(如果需要使用执行结果,就把它给一个变量)
def func_sum(num1, num2):
sum_num = num1 + num2
# print(sum_num)
return sum_num # return它的作用返回函数的执行结果,只能在函数内部使用
# 如果函数没有写返回值,默认返回函数就是None
result = func_sum(1, 4)
print(result)
# pr... |
55f235d755c6565242afbb4b9c9cd40dc65706ad | honey-kingdom/python | /OOP/1_Classes_and_Instances.py | 1,793 | 4.65625 | 5 | """
Python OOP Tutorial 1: Classes and Instances
"""
class Employee:
pass
emp_1 = Employee()
emp_2 = Employee()
print(emp_1)
print(emp_2)
emp_1.first = 'Corey'
emp_1.last = 'Schafer'
emp_1.email = 'Corey.Schafer@company.com'
emp_1.pay = 50000
emp_2.first = 'Test'
emp_2.last = 'User'
emp... |
47c6eff3713c348e45d79bfb2beea07e7d0e7065 | pascalmcme/myprogramming | /week7/labjson.py | 249 | 3.65625 | 4 | import json
filename = "testdict.json"
exampleDict = dict(
name = "Mary", age = 24, grades = [1,2,3]
)
def writeDict(obj):
with open(filename, "w") as f:
json.dump(obj,f) # two arguemts - the dict and the file name
writeDict(exampleDict) |
1212da7d117b990909f06ddbfa947264806c8b3f | moneyDboat/offer_code | /50_数组中重复的数字.py | 766 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
# @Author : captain
# @Time : 2018/10/30 1:20
# @Ide : PyCharm
"""
class Solution:
# 这里要特别注意~找到任意重复的一个值并赋值到duplication[0]
# 函数返回True/False
def duplicate(self, numbers, duplication):
# write code here
if not numbers:
return False
i =... |
a671d16233c640548177db2fd5ea4b07935385c1 | Jochizan/courses-python | /palindromes.py | 232 | 3.828125 | 4 | s = input('Ingrese una palabra a evaluar: ')
s = s.replace(' ', '')
s = s.lower()
tmp = s[::-1]
if tmp == s:
print("Es palindromo")
else:
print("NO es palindromo")
# codigo simple para verficar un palindromo con python :)
|
03f5132d64891b21ad81190616007f52d29b7927 | Midnight1Knight/HSE-course | /FifthWeek/Task6.py | 170 | 3.640625 | 4 | def null(n):
s = 0
while n != 0:
num = int(input())
if num == 0:
s += 1
n -= 1
return s
n = int(input())
print(null(n))
|
346c798b54a90e3e7774b184980bcff472daa170 | hz336/Algorithm | /LintCode/DS - Build In/Integer to Roman.py | 714 | 3.90625 | 4 | """
Given an integer, convert it to a roman numeral.
The number is guaranteed to be within the range from 1 to 3999.
https://en.wikipedia.org/wiki/Roman_numerals
"""
class Solution:
"""
@param n: The integer
@return: Roman representation
"""
def intToRoman(self, n):
# wr... |
561a6fdf1cfd70dfea345b8e1422e2f26ee35d50 | jaly50/LeetCode-python | /maxProfit1.py | 600 | 3.78125 | 4 |
# @param {integer[]} prices
# @return {integer}
# Jiali Chen
# 5/28/2015 Thu 14:42 am
# 121 Best Time to Buy and Sell Stock
# 维护一个最小值,最大值是减去到当前为止最小值
def maxProfit(prices):
n = len(prices)
if n<2:
return 0
minV = None
maxV = 0
for ele in pri... |
7478f4da3a323c88eadcedb0334b67485f9f496d | ArtisanTinkerer/scavenger | /main.py | 1,351 | 3.65625 | 4 | import csv
import random
from fpdf import FPDF
def load_all_items() -> list:
"""Real all items from the file into alist"""
with open('items.txt') as file:
items = file.read().splitlines()
return items
def input_integer() -> int:
"""Obtain an integer from the user"""
valid_integer = None
... |
feaa9efb33f33db3bef08899138de5b02a698647 | buttermilkcake/Python_Coding | /Python_Coding/ch_11_ex_11_3_employee.py | 1,144 | 4.125 | 4 | class People():
""""A simple attempt to represent some information."""
def __init__(self, name, salary):
"""Initialize people attributes."""
self.name = name
self.salary = salary
self.new_raise = 0
def get_descriptive_info(self):
"""Return a neatly... |
d3f9017f90001ab495ac238d0855b27908c028b9 | IvanWoo/coding-interview-questions | /puzzles/bst_find_modes.py | 1,588 | 3.96875 | 4 | # https://leetcode.com/problems/find-mode-in-binary-search-tree/
"""
Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than or equal to the no... |
8f76ebc011e06da35def50b4f05fff642d11324f | gitmengzh/100-Python-exercises | /100/q41.py | 247 | 3.96875 | 4 | '''
使用给定的元组(1,2,3,4,5,6,7,8,9,10)定义一个函数,第一行打印前一半数值,第二行打印第二半数值
'''
def printHarfTuple():
t = (1,2,3,4,5,6,7,8,9,10)
print(t[:5])
print(t[5:])
test = printHarfTuple()
|
eec319b2ec3f567250cc877422b086538e0974cf | miriamlam1/csc349 | /asgn1-miriamlam1/sort.py | 2,142 | 4.125 | 4 | import sys
import time
# A : unsorted list
# Selection Sort
# repeatedly selects the smallest element from the unsorted elements
def selection_sort(A):
for i in range(len(A)):
mini = i
for j in range(i+1, len(A)):
if A[j] < A[mini]:
mini = j
A[mini]... |
7797e0df5befff3fc93837cd5d8cc92300a29d49 | wslwlm/leetcode-practice | /103. Binary Tree Zigzag Level Order Traversal/Binary-Tree-Zigzag-Level-Order-Traversal.py | 3,680 | 3.671875 | 4 | # 题目地址: https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
# Runtime: 32 ms Memory Usage: 12.7 MB
# 借用层次遍历的做法, 用flag记录是否反转(可以简化为用奇偶判定),
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None... |
01703f0bc3dcd0b78ad6c6255ab29367566388c1 | afuous/surim-2018 | /code/ap-continuous.py | 1,060 | 3.546875 | 4 | import numpy as np
import itertools
import matplotlib.pyplot as plt
from random import random
def count_3APs(A,N):
total = 0
for a in range(0, N):
for b in range(1, (N-1)//2):
total += A[a] * A[(a + b) % N] * A[(a + 2 * b) % N]
return total
def main():
nsamples = 1000000
N = 23... |
3b03f33d0b47f400532e149f5cda380ed5d1a69b | petsc/petsc | /src/binding/petsc4py/demo/legacy/taosolve/rosenbrock.py | 3,631 | 3.578125 | 4 | """
This example demonstrates the use of TAO for Python to solve an
unconstrained minimization problem on a single processor.
We minimize the extended Rosenbrock function::
sum_{i=0}^{n/2-1} ( alpha*(x_{2i+1}-x_{2i}^2)^2 + (1-x_{2i})^2 )
"""
try: range = xrange
except NameError: pass
# the two lines below are on... |
b7bd5a1abb004a202813d4fa7737ab78d4affca6 | Ranyaron/euler | /euler2.py | 683 | 3.875 | 4 | '''Каждый следующий элемент ряда Фибоначчи получается при сложении двух предыдущих.
Начиная с 1 и 2, первые 10 элементов будут: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
Найдите сумму всех четных элементов ряда Фибоначчи, которые не превышают четыре миллиона.'''
a = 1
b = 1
c = 0
while True:
if a > 0:
a += ... |
7675274b328e6fa6ed58753a0119be04fa84407c | cybermin/pythonturtle | /Day1/Ex05.py | 408 | 3.984375 | 4 | """
python 예제 : N각형 그리기
"""
import turtle
# 입력
line = input("변의 길이를 입력하세요.")
# 입력된 내용은 문자열로 취급됨으로 정수로 변환
line = int(line)
n = input("n 각형의 n을 입력하세요.")
n = int(n)
# 다각형 그리기
for i in range(n):
turtle.forward(line)
turtle.left(360/n)
# 화면 유지
turtle.exitonclick() |
ad8db100079544c7d73f96395f00f42f591f5ace | rajarathod214/Python | /upper_lower.py | 146 | 3.6875 | 4 | #!usr/bin/python
message=raw_input("What is your name ?")
print message
print(message.lower())
print(message.upper())
print(message.swapcase())
|
9665209d2550bbb4bc442d9e5e3b365462c4b99f | xsupremeyx/GUI_Calculator_By_Supreme | /Calculator/MainCalc.py | 6,794 | 3.859375 | 4 | # Import
from tkinter import *
# Program Structure start
window = Tk()
window.title("Calculator")
color1 = '#%02x%02x%02x' % (217, 228, 241)
window.configure(bg='grey')
'''Structure continued ahead'''
# Program's Variables
op=1
operand1=[]
operator=[]
operand2=[]
sum=0
# Functions
def click(a):
... |
04417545dfa7a74e9e43633ba2d5e2b0bb033f98 | elsa1302/code_project | /GUI.py | 6,493 | 3.515625 | 4 | from tkinter import *
import tkinter as tk
import serial
import Execution_stm as gfe
class GuiWindow:
"""The Class GUIWindow includes all the front end features of the GUI """
def __init__(self, root, width, height, stm_protocols, perf_tests, title):
self.root = root
self.width = width
... |
11482fe11832e73065c320476196753d9bf2502e | nyasho4ka/crack_coding_interview | /arrays_and_strings/is_unique/test_is_unique.py | 1,141 | 3.53125 | 4 | import is_unique
import unittest
class IsUniqueTestCase(object):
def test_unique_string(self):
unique_string = 'abcde'
self.assertEqual(self.is_unique(unique_string), True)
def test_non_unique_string(self):
non_unique_string = 'aabbccee'
self.assertEqual(self.is_unique(non_uni... |
638acd199b2eba067488da253986874cdefe0041 | MateoKrile/Elements-of-AI---Building-AI | /Section 3 Machine Learning/Working with text/Bag of words.py | 1,765 | 4.46875 | 4 | """
Your task is to write a program that calculates the distances (or differences) between every pair of lines in the
This Little Piggy rhyme and finds the most similar pair. Use the Manhattan distance as your distance metric.
You can start by building a numpy array to store all the distances. Notice that the diagona... |
0186a44a90735716d421714b5b5cdb9bd0692576 | amovah/ACM | /QueraIR/2.py | 132 | 3.703125 | 4 | max = 0
for i in range(int(input())):
current = set(input())
if len(current) > max:
max = len(current)
print(max)
|
94f8ec83b101f7e3ef2ca488bbee3e217af448cc | AlexandraFil/Geekbrains_2.0 | /Python_start/lesson_5/lesson_5.3.py | 897 | 4.21875 | 4 | # 3. Создать текстовый файл (не программно), построчно записать фамилии сотрудников и величину их окладов.
# Определить, кто из сотрудников имеет оклад менее 20 тыс., вывести фамилии этих сотрудников.
# Выполнить подсчет средней величины дохода сотрудников.
wages = {}
with open('lesson_5.3.txt', 'r', encoding='utf-8')... |
70cc7fcb8567698f2aed1d73c72eec47bba35264 | EuniceHu/python15_api_test | /Myself/class_214_str_tuple_list_dict/class_tuple.py | 1,034 | 3.859375 | 4 |
#整数 浮点数 字符串 布尔值 True False
#元祖 关键字 tuple
#1:特征
#1.1.圆括号括起来的数据,都是元祖
#1.2.空元祖 t_1=()
#1.3.如果一个元祖里面只有一个元素,要在元素后面加一个逗号
#1.4 元祖里面可以包含各种类型的数据 整数 浮点数 字符串 布尔值
#1.5 元素与元素之间是用逗号隔开的,看元素的长度 len
#1.6 取值方式:与字符串一样 根据索引取值 可以切片取值
#取单个值的方式 元祖名[索引值] 索引值从0开始
#嵌套取值 怎么取
# t_1=(2,0.0089,'1',True,(1,2,3,'hello'))
# s=t_1[-1]#取出值 ... |
a375c1710040b8cad8ed00f8fb7a9fe600680a7d | shivakrshn49/python-concepts | /bound_vs_unbound_methods.py | 1,584 | 3.765625 | 4 | #https://stackoverflow.com/questions/13348031/python-bound-and-unbound-method-object
#Whenever you look up a method via instance.name (and in Python 2, class.name), the method object is created a-new.
#Python uses the descriptor protocol to wrap the function in a method object each time.
#So, when you look up id(C.fo... |
6c7bbfbc165ea61089e1edd47cbf79ff5bb503b4 | maohaoyang369/Python_exercise | /152.遍历一个列表[1,2,3,4,5,1],请判断列表里面是否有1,有的话打印findit,没有的话提示,没有1.py | 429 | 3.671875 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
# 遍历一个列表[1,2,3,4,5,1],请判断列表里面是否有1,有的话打印find it,没有的话提示,没有1
sentence = [1, 2, 3, 4, 5]
is_break = False
for i in sentence:
if not isinstance(i, (int, float)):
print("None")
elif i == 1:
print("find it!")
break
elif i != 1:
is_bre... |
eb2ac5d889273149ad42386393cd403f94f92fd4 | 7enTropy7/Tic-Tac-Toe_AI | /ttt.py | 2,655 | 3.765625 | 4 | def toggle(player):
if player == 'X':
return 'O'
else:
return 'X'
class Game:
def __init__(self):
self.board = [' ']*9
def minimax_algorithm(self,node,depth,player):
if depth == 0 or node.draw():
if node.check() == "X":
return 0
e... |
256810dcadab649f0696ccec9d8b4b10193c36d2 | moontasirabtahee/OOP_Python_BRACU | /CSE111 Lab Assignment 6/Task9.py | 1,476 | 3.734375 | 4 | # Created by Moontasir Abtahee at 6/8/2021
class Student:
t_stu=0
brac_stu=0
other_stu=0
def __init__(self, name, dept, ins='BRAC University'):
self.name = name
self.dept = dept
self.ins = ins
Student.t_stu += 1
if self.ins == 'BRAC University':
Stude... |
e267f8d15bd01a0e3b4cc61f6f4a4a429689ba1c | niru23/algorithms | /movezeros.py | 769 | 3.703125 | 4 | #!/usr/bin/python
import unittest
def movezeros(array):
i =0
j =1
while i <len(nums)-1 and j<len(nums):
if nums[i] !=0 :
i+=1
j+=1
elif nums[i]== 0 and nums[j] ==0:
j+=1
elif nums[i] ==0 and nums[j]!... |
c4435eabc1db731be246bc1619579e807ffc97c9 | bsummerset/exercises | /python/sequences/med_3.py | 125 | 3.640625 | 4 | num = [[2,4,6,4], [3,7,5,9]]
new = []
for num[0], num[1] in zip(num[0], num[1]):
new.append(num[0] + num[1])
print(new) |
b36f62160f6610a54c2bc1204aacb6a720879fce | Sahil-Ovhal/CS_Dojo | /weather/graphs.py | 606 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 19 21:01:08 2019
@author: Admin
"""
import matplotlib.pyplot as plt
import numpy as np
import math
## Create functions and set domain length
x = np.arange(-5.0, 5.0, 0.01)
y = x**x
z=0
## Plot functions and... |
11fb1a87c0d5e8b929e21fb4dfc47cf625684a03 | HarshaMatta/PythonProjects | /F_to_C.py | 594 | 4.34375 | 4 | # created by harsha matta
# created on 26/10/18
# this program will convert celsius to fahrenheit and vice versa
# this program takes two inputs: type of temperature you start with and the number that you want to convert
# then it output the converted temperature
def fahrenheit(number):
print( float((number - 32) ... |
e80abb98a565aa3bf985269f626011127c05d3b3 | Leonard-Atorough/python-practice | /example_a.py | 320 | 3.828125 | 4 | a = "A B C D E F"
b = "Y B H D A G"
def first_difference(str1, str2):
difference = ""
set_a = set(a)
set_b = set(b)
for word_a in set_a:
if word_a not in set_b:
if word_a not in difference:
difference += word_a
print(sorted(difference))
first_difference(a... |
9f6efc997bbaa486dfcd91670a41c8aa2cfd03ab | vdudi/playwithpython | /fileOpen.py | 373 | 3.71875 | 4 | file = input("Enter File Name, like email-short.txt: ")
try:
#fhand = open('mbox-short.txt')
fhand = open(file)
except:
print("Exception, file not found")
#inp = fhand.read()
#print((len(inp)))
#print("111 "+ inp[:20])
for line in fhand:
if line.startswith('From:'):
line = line.rstrip()
... |
9dae4620d627e4cd7ec7459b92fe3eb5fd44ce58 | nirakarmohanty/Python | /controlflow/WhileExample.py | 100 | 3.78125 | 4 | #Print the number from 1->10
i=0;
while i < 10:
print(i);
i=i+1;
print("latest value :",i);
|
5b6d3ea80843e1ddc43f740311233765cbc534d4 | xiao-bo/leetcode | /medium/swapNodeInPairs.py | 1,465 | 3.953125 | 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):
"""
:type head: ListNode
:rtype: ListNode
"""
## iteration method by me
## I spend... |
09ed7213c04674928c5e183106b350ade30791a0 | Nishith170217/Python-Self-Challenge | /List Program/Sort the values of first list using second list in Python.py | 333 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 30 16:52:52 2021
@author: Nishith
"""
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for c, x in sorted(zipped_pairs)]
return z
x = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]
print(sort_... |
8359b8f7612cdc744ddb66acd170a813a0cb2941 | ResearchInMotion/CloudForce-Python- | /UnboxQuestions/F-19.py | 146 | 3.578125 | 4 | def girl(str,c):
if(c in str):
return("1")
else:
return("0")
print("The character is present or not ",girl("chinky","n")) |
549fbdb1cee15b9285b297b7f8536c84e4f913f6 | Miked7531/Python | /pieabstract.py | 396 | 3.8125 | 4 | from abc import ABC, abstractmethod
class pie(ABC):
def pieSlice(self, amount):
print("Your slice of the pie is: ",amount)
@abstractmethod
def piethief(self, amount):
pass
class Totalpieslices(pie):
def piethief(self, amount):
print('You have stolen {} slices of pie!!'.... |
a6e9b0022f9f8d6d9d2fb1bda9798922cb7a413c | syurskyi/Python_Topics | /070_oop/004_inheritance/examples/super/0001.py | 3,284 | 4.71875 | 5 | # The super() builtin returns a proxy object (temporary object of the superclass) that allows us to access methods
# of the base class.
# In Python, super() has two major use cases:
#
# Allows us to avoid using the base class name explicitly
# Working with Multiple Inheritance
# Example 1: super() with Single Inherita... |
6c0614461a1d930c0ddf91d8fa2f0fae92f4f89f | randylodes/Coursera | /pay-calculator.py | 261 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 16 13:52:15 2017
@author: Randy
"""
# Gather the input data
hrs = input("Enter hours: ")
rate = input("Enter rate: ")
# Calculate the result
pay = float(hrs) * float(rate)
# Output the result
print("Pay:", pay) |
3eeb32cccd9753566f185b01dd6e88da17b92561 | StartAmazing/Python | /venv/Include/tuling/chapter1/strfunc.py | 2,182 | 4.5 | 4 | # str 内置函数
# 字符串的查找
str = "hello, java, python and Scala"
print(str.find("Scala"))
# print(str.index("C++")) # value error
print(help(str.find))
# 判断类函数
print(str.islower())
# 判断是否全部是字母或汉字字符
print(str.isalpha())
print("Linus".isalpha())
print("你好".isalpha())
print( "-----------------------isdigit, isnumeric, isdeci... |
fa6e214260d065003c42711480659142c9ca4982 | kellyseeme/pythonexample | /323/isString.py | 762 | 4.46875 | 4 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
#this is test a string is a string or not
#this is use isinstance to check is this a string
def isString(x):
return isinstance(x,basestring)
print map(isString,["kel",34,u"ko"])
#this is use the duck string to test a string is a string
def isStringLike(obj):
try:... |
1d9154fcdf96fd895b650c2e6109ae266ea60bdb | jaeyoung-jane-choi/2016-2021_Sungkyunkwan_University | /2020-Data-Structure-Algorithms/bfs.py | 956 | 3.84375 | 4 |
# from clqueue import Queue #큐를 한 과제가 없어서, 큐를 새로 정의했습니다.
#first in first out
class Queue:
def __init__(self):
self.item = [] #empty list
def is_empty(self):
return self.items == []
def enqueue(self,item):
self.item.append(item) #append at first
def dequeue(self):
if... |
784a4888ee8851d1cd065f8bce0dcbead5409526 | s1s1ty/Calculator | /Calculator.py | 2,856 | 3.75 | 4 | from tkinter import *
import math
root = Tk()
root.resizable(0,0)
equa = ""
root.title("Shaonty's Calculator")
#Display
num1 = StringVar()
e = Label(root,textvariable=num1,height=3,width=25,font=150)
e.grid(columnspan = 4)
def btnPress(num):
global equa
equa = equa+str(num)
num1.set(equa)
def equalPress():
gl... |
c8d996e9a89e5ac05ebda1538225cea697537009 | kk2491/Probability_Distributions | /Exponential_Distribution/Exponential_Distribution_Python_1.py | 611 | 3.546875 | 4 | '''
mean = 1 / lambda
variance = 1 /(lambda)^2
'''
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
lambd =0.5
x = np.arange(0, 15, 0.1)
y = lambd * np.exp(-lambd * x)
plt.figure(1)
plt.plot(x, y)
plt.title('Exponential: $\lambda$ = %.2f ' % lambd)
plt.xlabel('x')
plt.ylabel('Probabili... |
1722671a152ef77a2b7ff58723e4843ef387ba66 | tnakaicode/jburkardt-python | /triangle_grid/triangle_integrals.py | 58,010 | 3.953125 | 4 | #! /usr/bin/env python3
#
def i4_to_pascal_degree(k):
# *****************************************************************************80
#
# I4_TO_PASCAL_DEGREE converts a linear index to a Pascal triangle degree.
#
# Discussion:
#
# We describe the grid points in Pascal's triangle in ... |
8828a4c23e6bc1a580b0e2b82647a629cdb4652d | LorranSutter/HackerRank | /Mathematics/Geometry/Points_On_a_Line.py | 407 | 3.640625 | 4 | #!/bin/python3
if __name__ == '__main__':
n = int(input())
points = []
for _ in range(n):
x, y = map(int, input().split())
points.append([x, y])
horizontal = [points[k][0] == points[k+1][0] for k in range(n-1)]
vertical = [points[k][1] == points[k+1][1] for k in range(n-1)]
i... |
c042dd221e00fd2ad85a1246b512164b31bfbf8d | saulhappy/algoPractice | /python/miscPracticeProblems/Fundamentals/revString.py | 84 | 3.75 | 4 | word = "saul"
def revString(word):
return word[::-1]
print(revString(word))
|
a9d9ad6aec6907e28c53341cec5d5baba2760981 | Rahul91/pytest | /simple_class.py | 290 | 3.59375 | 4 | class Person:
def set_details(self, name, age):
self.name = name
self.age = age
def get_details(self):
return self.name, self.age
obj1 = Person()
obj2 = Person()
obj1.set_details("Rahul", 23)
obj2.set_details("Bittu", 26)
print obj1.get_details()
print obj2.get_details()
|
b9adae0dfb386b2cb47d2336260b32f4819eb46b | LeonVillanueva/Projects | /Daily Exercises/daily_6.py | 1,138 | 4.15625 | 4 | '''
Given a array of numbers representing the stock prices of a company in chronological order, write a function that calculates the maximum profit you could have made from buying and selling that stock. You're also given a number fee that represents a transaction fee for each buy and sell transaction.
You must b... |
97bc705cecd26a377627218464f588c38662ef72 | ccjoness/CG_StudentWork | /Skip/unsorted/divisors.py | 581 | 4.34375 | 4 | # Create a program that asks the user for a number and then prints out a list
# of all the divisors of that number. (If you don’t know what a divisor is, it
# is a number that divides evenly into another number. For example, 13 is a
# divisor of 26 because 26 / 13 has no remainder.)
# Remember you can generate a list ... |
de5f6df4fad4731e677a52c7ee7cf76978f4d9ad | ndbellew/PythonProjects | /OOP/initIntroducion.py | 295 | 3.671875 | 4 | #initIntroducion.py
class Point:
def __init__(self,x,y):
self.move(x,y)
def move(self,x,y):
self.x=x
self.y=y
def reset(self):
self.move(0,0)
# Constructing a Point
point = Point(3, 5)
point.z = 4
print(point.x, point.y, point.z)
point.reset()
print(point.x, point.y, point.z)
|
551a368e955c36d6f4bea32f3b9d18e4ba3039db | LuizFernandoR/CursoPython | /Praticando/Exercicio01.py | 253 | 3.59375 | 4 | lista1 =[1,2,3,4,5,6,7,8,9,10]
lista2 =[10,9,8,7,6,5,4,3,2,1]
soma = 0
produto = 0
for i in lista1:
for j in lista2:
soma= i + j
produto= i * j
print('Lista soma:',soma,'- Lista produto:',produto)
|
b67f259ace3503413d63f5bb4900b1a4dc9fa86a | h4x0rlol/codewars | /playingwithdigits.py | 229 | 3.5 | 4 | def dig_pow(n, p):
res = 0
numbers = list(map(int, str(n)))
for number in numbers:
res += number**p
p = p+1
k = res//n
if(res % n == 0):
return k
return -1
print(dig_pow(212, 6))
|
d14aa4306cb1b10e25342a4b6a4ada32724b0908 | manonansart/rosalind | /fibd.py | 455 | 3.53125 | 4 | # http://rosalind.info/problems/fibd/
import sys
n = int(sys.argv[1])
m = int(sys.argv[2])
if m == 0:
print 0
elif m == 1:
if n == 1:
print 1
else:
print 0
elif n == 1:
print 1
else:
f1 = 1
f2 = 1
f = 1
births = [1, 0]
for i in range(3, n+1):
if i < m+1:
f = f1 + f2
f2 = f1
f1 = f
fm... |
1aec4c2343dcbee8fb344707b0c2f682a43401f4 | drichardson/examples | /python/closure.py | 188 | 3.53125 | 4 | def foo():
print("foo")
for i in range(0, 10):
print("i: {}".format(i))
loop_var = {'val': i}
f = lambda x: print(loop_var.get(x))
f('val')
foo()
|
00d05f4a45b4156647a0763b16edaa78d4ca71de | crowjdh/QuesStudyCabinet | /180518/codefight/arcade/core/JungDongHyun/7. lateRide.py | 320 | 3.609375 | 4 | def lateRide(n):
hours_past = n / 60
minutes_past = n - (hours_past * 60)
result = 0
result += sum_digits(hours_past)
result += sum_digits(minutes_past)
return result
def sum_digits(n):
total = 0
while n > 0:
total += n % 10
n /= 10
return total
|
20dd569c4ad791aca11c9a2ada490ed5515eeff0 | Dylan-Cairns/Package_Delivery_Scheduler | /sort_algorithm.py | 1,388 | 4.0625 | 4 | import data_structures
# this method contains the algorithm which, given a list of packages,
# chooses the order of packages for delivery. time complexity: O(N^2)
def choose_delivery_order(packages_list):
current_location_id = 0
unordered_list = packages_list.copy()
ordered_list = []
total_mileage = ... |
53b217c63d4e486c923a778b2e3ae027351aaf2b | Mohit-Sharma1/Takenmind_Internship_assignments | /Section2/L8 Conditional clause and boolean operations/conditional_and_boolean.py | 538 | 3.59375 | 4 | import numpy as np
x= np.array([100,400,500,600]) #each member pf 'a'
y=np.array([10,15,20,25]) #each member of 'b'
condition=np.array([True,True,False,False]) #each member cond.
#add some boolean expersion
#use loops indirectly to perform this
z=[a if cond else b for a,cond,b in zip(x,condition,y)] #this is s... |
200385e0c3532ed2ba927efa251cea88db7aa2d9 | hopdino/actor-model | /actor_model/chapter06/examples/actors_cooperating_counts.py | 1,032 | 3.53125 | 4 | """
Multiple cooperating actors
本例子是展示多个actor之间的通信.
多个actor 一起数数.
"""
import threading
from actor_model.chapter06.actor_register import ActorRegistry
from actor_model.chapter06.threading import ThreadingActor
class Adder(ThreadingActor):
"""
我负责统计
"""
def add_one(self, i):
print(f"{self} is i... |
63555014647d9e6e96cab2a742cd6ee0c5b5c569 | april9288/ds_algorithms | /Sort Algorithms/selection.py | 274 | 4 | 4 | def selectionSort(array):
for i in range(0, len(array)):
minimum = i
for j in range(i+1, len(array)):
if array[j] < array[minimum]:
minimum = j
temp = array[minimum]
array[minimum] = array[i]
array[i] = temp
return print(array)
selectionSort([6,5,0,1]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.